0

I need to append the css and js file dynamically and am using below method

document.getElementsByTagName('head')[0].appendChild(); 

this method doesn't allow second parameter. I have to append both the css and js file dynamically. I am calling the above method twice to append the files. Any other generic way to restrict the above method to be called only once.

Here it is what i have tried:

var jscss = function(cp, sp){

    var css = document.createElement("link");
    css.setAttribute("rel", "stylesheet");
    css.setAttribute("type", "text/css");
    css.setAttribute("href", cp);
    document.getElementsByTagName('head')[0].appendChild(css);

    var script = document.createElement('script');
    script.src = sp;
    document.getElementsByTagName('head')[0].appendChild(script);

};

jscss();
Vikash Pandey
  • 5,407
  • 6
  • 41
  • 42

3 Answers3

1

Well, I think you can achieve it by providing id to the element and before appending it just check if that element exists. Example:

 var jscss = function(cp, sp){

    if(!document.getElementById("customStyleSheet")){
        var css = document.createElement("link");
        css.setAttribute("rel", "stylesheet");
        css.setAttribute("id", "customStyleSheet");
        css.setAttribute("type", "text/css");
        css.setAttribute("href", cp);
        document.getElementsByTagName('head')[0].appendChild(css);
    }

    if(!document.getElementById("customScript")){
        var script = document.createElement('script');
        script.src = sp;
        script.id = "customScript";
        document.getElementsByTagName('head')[0].appendChild(script);
    }

    };

    jscss();

Hope this will help you :)

Vikash Pandey
  • 5,407
  • 6
  • 41
  • 42
0

Use a variable to remember if the function has run already.

var jscss_run = false;
function jscss(cp, sp) {
    if (jscss_run) {
        return; // don't run a second time
    }
    jscss_run = true;
    // do all the real work
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You could use a documentfragment in order to only need to call to appendChild once to add both elements:

var jscss = function(cp, sp){

  var fragment = document.createDocumentFragment();

  var css = document.createElement("link");
  css.setAttribute("rel", "stylesheet");
  css.setAttribute("type", "text/css");
  css.setAttribute("href", cp);
  fragment.appendChild(css);
  //Does not affect the DOM

  var script = document.createElement('script');
  script.src = sp;
  fragment.appendChild(script);
  //Does not affect the DOM

  document.getElementsByTagName('head')[0].appendChild(fragment);
  //Adds both elements to the DOM
};

jscss();
Stephan
  • 591
  • 4
  • 7