开发者

Can I register external JS files on a page via Javascript?

开发者 https://www.devze.com 2022-12-16 17:04 出处:网络
In my CMS I add modules to the page via Javascript, these modules may i开发者_如何学JAVAnclude external JS files which get registered on page load into a collaborated external file.

In my CMS I add modules to the page via Javascript, these modules may i开发者_如何学JAVAnclude external JS files which get registered on page load into a collaborated external file.

When the modules are added via JS these scripts are therefore not registered until the page is reloaded.

Is there a way for me to register these scripts dynamically via the javascript calls in the mean time?


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(
    '<script src="path/to/script.js" type="text/javascript"><\/script>'
);


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
  //..
});

function loadScript(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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消