在正常的加載過程中,js的加載都是同步的,也就是在加載過程中,瀏覽器會阻塞接下來的內容的加載。這時候我們就要用到動態加載,動態加載是異步的,如果我們在后邊要用到這個動態加載的js文件里的東西,就要保證這個文件加載完成后,再執行下面的內容。
如何判斷js是否加載完成?(實現loadScript(url,callback)異步加載腳本,完成后執行回調函數,要求支持IE)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>js判斷異步引入的js文件是否加載完畢</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
</head>
<body>
<p onclick="loadScript('ocrad.js',null);">js如何判斷異步引入的js文件是否加載完畢</p>
<script type="text/javascript">
function loadScript(url,callback){
//但是,這種加載方式在加載執行完之前會阻止 onload 事件的觸發
var _doc=document.getElementsByTagName('head')[0]; //獲取head頭部標簽元素對象。
var script=document.createElement('script'); //創建一個script標簽元素。
script.setAttribute('type','text/javascript'); //設置script標簽的type屬性。 script.type='text/javascript'
//script.async='async';
script.setAttribute('src',url); // script.src=url;
script.setAttribute('async','true');
_doc.appendChild(script); //將script標簽附加到head標簽中,否則只能夠在IE11以下瀏覽器能夠完成判斷。
script.onload=script.onreadystatechange=function(){
if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){
console.log('js onload');
}
script.onload=script.onreadystatechange=null; //刪除事件處理函數。
}
}
//解決了阻塞 onload 事件觸發的問題 ,不是立即開始異步加載 js ,而是在 onload 時才開始異步加載。
if (window.attachEvent)
window.attachEvent('onload', function(){loadScript('ocrad.js',null);});
else
window.addEventListener('load', function(){loadScript('ocrad.js',null);}, false);</script>
</body>
</html>
