js判断异步引入的js文件是否加载完毕

  在正常的加载过程当中,js的加载都是同步的,也就是在加载过程当中,浏览器会阻塞接下来的内容的加载。这时候咱们就要用到动态加载,动态加载是异步的,若是咱们在后边要用到这个动态加载的js文件里的东西,就要保证这个文件加载完成后,再执行下面的内容。javascript

  如何判断js是否加载完成?(实现loadScript(url,callback)异步加载脚本,完成后执行回调函数,要求支持IE)html

<!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>

相关连接:http://www.javashuo.com/article/p-hadhxcsw-h.htmljava

http://www.javashuo.com/article/p-dloglayf-cn.htmlchrome

相关文章
相关标签/搜索