Three ways to load a JS file dynamically

  • 2020-03-26 23:48:06
  • OfStack

Just look at the example.
Example 1 reloads the js file

function loadJs(file) {
            var head = $("head").remove("script[role='reload']");
            $("<scri" + "pt>" + "</scr" + "ipt>").attr({ role: 'reload', src: file, type: 'text/javascript' }).appendTo(head);

Example 2: the method of reloading javascript files (giving js an id) is encapsulated as a method for everyone to use:

function reloadAbleJSFn(id,newJS)
var oldjs = null; 
var t = null; 
var oldjs = document.getElementById(id); 
if(oldjs) oldjs.parentNode.removeChild(oldjs); 
var scriptObj = document.createElement("script"); 
scriptObj.src = newJS; 
scriptObj.type = "text/javascript";   = id; 

For example 3 jquery, just use getScript.

<script type="text/javascript" src="../jquery.js"></script> 
<script type="text/javascript"> 
newFun('"Checking new script"');//This function is inside new.js and runs when you click click
<button type="button" id="loadButton">Load</button>

Related articles: