SoFunction
Updated on 2025-02-28

Three ways to dynamically load JS files

Look directly at the examples.
Example 1 Reload the js file
Copy the codeThe code is as follows:

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 the javascript file (set an id for js), encapsulate it into a method that is convenient for everyone to use:
Copy the codeThe code is as follows:

function reloadAbleJSFn(id,newJS)
{
var oldjs = null;
var t = null;
var oldjs = (id);
if(oldjs) (oldjs);
var scriptObj = ("script");
= newJS;
= "text/javascript";
   = id;
("head")[0].appendChild(scriptObj);
}
 

Example 3: Just use getScript directly for jquery.
Copy the codeThe code is as follows:

<script type="text/javascript" src="../"></script>
<script type="text/javascript">
$(function()
{
$('#loadButton').click(function(){
$.getScript('',function(){
newFun('"Checking new script"');//This function is inside. When clicking on the function to run
});
});
});
</script>
</head>
<body>
<button type="button" >Load</button>