问题
We are using backbone routing, mod_rewrite, requirejs. The app is in a folder, not on the web root, so relative folder references are required for images,css, and js files (if we could use absolute folders the files would load).
When accessing a route with a trailing slash none of the js and css files loads correctly unless there is an appropriate base tag set in the header. Like so:
<base href="//localhost/myapp/" />
This solution works. The problem is we need to variablize the base tag so that we can have dev and production versions of the code. But to load a js file with the variable wont work without a base tag.
Just to be sure I did the standard fixes for backbone. Fix optional slash (/):
routes: {
'faq(/)':'jumpToText',
'register(/)':'jumpToForm',
},
And setting the root in history
Backbone.history.start({pushState: true, root: "//localhost/myapp/");
The problem appears to be an unresolvable mod_rewrite issue. So the final thought is to dynamically set the base tag.
回答1:
We ultimately used JavaScript to parse the value out of location.href . Wrap this code in a script tag in the head:
document.write("<base href="+'//'+document.location.host +'/'+ location.href.split('/')[3]+'/'+" />");
And did the same in routes.js (parsing out the uri)
Backbone.history.start({pushState: true, root: "/"+location.href.split('/')[3]});
回答2:
A working solution that I have to account for protocol / host / port is the following
var base = document.createElement('base');
base.href = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
document.getElementsByTagName('head')[0].appendChild(base);
This currently works fine in all major browsers including IE11 (Which does not support window.location.origin)
I have used this to make an npm package that also supports adding a suffix to the end of this base href if anyone is interested
https://www.npmjs.com/package/dynamic-base
https://github.com/codymikol/dynamic-base
来源:https://stackoverflow.com/questions/20308395/how-to-dynamically-set-the-base-tag