How to dynamically set the base tag?

2019-06-03 05:18发布

问题:

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]});