Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert external stylesheet in JavaScript (dynamically)

Tags:

javascript

...with right path.

For example. I have script called foo.js. I'd like to insert stylesheet declaration which I can do with following instruction:

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

Problem: I have to put full path to the stylesheet file. So instead of /template/foo.css I have to put: http://hostname/directory/template/foo.css. I can't set it statically beacause script can be placed in different servers and different locations. So it can be: http://foo.com/bar/foo.css or http://foo.com/foo.css.

It would be very useful if I can get path of foo.js file on the server. That would be good enough beacause then I could set stylesheet location based on the javascrpt's file.

like image 842
Bald Avatar asked Jan 23 '23 19:01

Bald


2 Answers

I've always done:

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

instead of head

Ahh... sorry I just realised what your problem is. One strategy is to extract the path of 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" />'
                        );
    }
})
like image 117
slebetman Avatar answered Mar 02 '23 18:03

slebetman


This is a common technique 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 basically because when the script is being executed, it is the last script tag on the DOM.

like image 30
Christian C. Salvadó Avatar answered Mar 02 '23 16:03

Christian C. Salvadó