Dynamically load the JS file and execute its own callback function according to the loading state of the JS file,
In many scenarios, we need to perform subsequent operations according to the loading state when dynamically loading JS files. After the JS is loaded successfully, another method needs to be executed. This method is based on the loaded JS file (calling The method in this JS, etc.), at this time, this method needs to be executed as a callback function after JS is loaded
Specific examples:
JS code is as follows
function
loadJs(loadUrl,callMyFun,argObj){
var
loadScript=document.createElement(
'script'
);
loadScript.setAttribute(
"type"
,
"text/javascript"
);
loadScript.setAttribute(
'src'
,loadUrl);
console.log(loadUrl)
document.getElementsByTagName(
"head"
)[0].appendChild(loadScript);
//判断服务器
if
(navigator.userAgent.indexOf(
"IE"
) >=0){
//IE下的事件
loadScript.onreadystatechange=
function
(){
if
(loadScript && (loadScript.readyState ==
"loaded"
|| loadScript.readyState ==
"complete"
)){
//表示加载成功
loadScript.onreadystatechange=
null
;
callMyFun()
//执行回调
}
}
}
else
{
loadScript.onload=
function
(){
loadScript.onload=
null
;
callMyFun();
}
}
console.log(argObj);
}
function
loadJsBtn(){
//如需传参
var
argObj={};
loadJs(
"js/jqueryww.js"
,callMyFun,argObj);
}
function
callMyFun(){
alert(
"执行我的回调啊"
)
}
HTML code
<
button
onclick="loadJsBtn()">加载JS文件</
button
>