How to insert an external stylesheet in JavaScript (dynamically)

... with the right path.

For instance. I have a script called foo.js. I would like to insert a style declaration, which I can do with the following statement:

$('head').append('<link rel="stylesheet" href="/template/foo.css" type="text/css" />'); 

Problem . I have to specify the full path to the stylesheet file. So instead of /template/foo.css I have to put: http: //hostname/directory/template/foo.css . I can not install it statically beacause the script can be hosted on different servers and in different places. So it could be: http://foo.com/bar/foo.css or http://foo.com/foo.css .

It would be very helpful if I could get the path to the foo.js file on the server. That would be good enough, because I could set the style sheet location based on the javascrpt file.

+4
source share
3 answers

I always did:

 $('body').append('<link rel="stylesheet" href="/template/foo.css" type="text/css" />'); 

instead of head

Ah ... sorry, I just realized what your problem is. One strategy is to extract the path from the script from the DOM itself:

 $('script').each(function(i,el){ var path = el.src.match(/^(.+)\/foo.js$/); if (path) { $('body').append('<link rel="stylesheet" ' + 'href="' + path[1] + '/foo.css" ' + 'type="text/css" />' ); } }) 
+7
source

This is the general method that I use to get the current script url:

 var scriptUrl = (function() { var scripts = document.getElementsByTagName('script'), script = scripts[scripts.length - 1]; return script.src; })(); 

It works mainly because when the script is executed, this is the last script tag in the DOM.

+2
source

You can use window.location and get the path from this. For example, for this page it is:

 >>> window.location http://stackoverflow.com/questions/2033742/how-to-insert-external-stylesheet-in-javascript-dynamically 
0
source