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

In my CMS, I add modules to the page through Javascript, these modules can include external JS files that are registered when the page is loaded into an external file.

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

Is there a way to register these scripts dynamically through javascript calls on average?

+1
source share
2 answers

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 can also use document.getElementsByTagName("head")[0] for head var. Alternatively, you can use document.write , for example:

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

I made the following function based on the jQuery $.getScript , it takes url and callback arguments.

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

This function also takes care of removing script elements from the DOM to avoid 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); } 
+1
source

Source: https://habr.com/ru/post/1336583/


All Articles