Skip to content Skip to sidebar Skip to footer

Can I Register External Js Files On A Page Via Javascript?

In my CMS I add modules to the page via Javascript, these modules may include external JS files which get registered on page load into a collaborated external file. When the modul

Solution 1:

You can add a script tag to your page using the following code:

var head  = document.documentElement.childNodes[0];
var sTag  = document.createElement("script");
sTag.src  = "/path/to/script.js";
sTag.type = "text/javascript";
head.appendChild(sTag);

You could also use document.getElementsByTagName("head")[0] for the head var. Alternatively, you could use document.write, like so:

document.write(
    '<scriptsrc="path/to/script.js"type="text/javascript"><\/script>'
);

Solution 2:

I made the following function, inspired by the jQuery's $.getScript method, it takes an url and a callback argument.

The callback is very useful, it is executed when the script has been loaded successfully, and you are ready to use it.

This function also takes care of removing the script elements from the DOM to avoid well known memory leaks:

loadScript("myLib.js", function () {
  // myLib is loaded//..
});

functionloadScript(url, callback) {
  var head = document.getElementsByTagName("head")[0],
      script = document.createElement("script"),
      done = false;

  script.src = url;
  // Attach event handlers for all browsers
  script.onload = script.onreadystatechange = function(){
    if ( !done && (!this.readyState ||
      this.readyState == "loaded" || this.readyState == "complete") ) {
      done = true;
      callback(); // Execute callback function// Prevent memory leaks in IE
      script.onload = script.onreadystatechange = null;
      head.removeChild( script );
    }
  };
  head.appendChild(script);
}

Post a Comment for "Can I Register External Js Files On A Page Via Javascript?"