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"; 
scriptObj.id   = id; 
document.getElementsByTagName("head")[0].appendChild(scriptObj);
}
 

For example 3 jquery, just use getScript.

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

Related articles: