I'm trying to work with requirejs and text plugin and I have weird problem.
I have two web servers:
- localhost:3000 - act as CDN and has all the static files: js, images, css and templates
- localhost:3001 - server - act as REST server and serve only one file, the main.html file
The main.html file loads all the js files from the second server using the following line:
<script data-main="http://localhost:3000/js/main"
src="http://localhost:3000/lib/require-jquery.js"></script>
For some reason, when using the requirejs text plugin, he adds to the templates ".js"
suffix when navigating to localhost:3001
I'm using the following syntax:
define ['jquery','backbone','underscore','models/model','text!templates/main.html',
'views/navigation', 'views/player', 'views/content', 'views/header']
when I navigate to localhost:3000 it works fine.
Can you think of any reason that the text plugin would have problems serving text files from a remote server (for example, CDN server)?
I ran into the same problem and the fix was to make sure the main.js file was loaded from the same domain as the *.htm files. When they differed, require would append the .js to the html files, resulting in 404s.
I've hacked at every solution I've seen posted on the internet aside from running r.js optimizer and compiling my templates into .js file.
A temporary work around is to put your templates in the same directory as your index.html file. This of course doesn't solve the problem but if you are at a standstill like I was, then this will at least get you moving again.
The documentation of the text plugin gives a hint to the solution: It's possible to configure the plugin in a way that it always fetches remote resources via XHR without appending the
.js
suffix and loading it via script tag. The simple solution is to always enforce using XHR:Note that the remote server needs to set the correct CORS header and that this could be a security issue. Thus add the necessary checks for trusted urls when using this instead of simply returning
true
.I've digged in the code of the text plugin.
I've found out that the text plugin assumes that the developer converted the text template to html since it resides on a different domain.
I've change the code of the text plugin to not assume it.
Someone thinks that I'm doing something wrong?
The original code of the plugin:
Such config does not work in current text! plugin. My solution was in overriding useXhr method in 'text' module
As another alternative way you can use jQuery get method to fetch the content of the template as plain text and then compile it with Handlebars. I came to this solution as a last resort after spending several hours into forums reading about issues with require.js text plugin and CORS. Here's an example :
The template :
The js script :