导航

异步函数回调

Posted on 2018-05-15 19:07  小飞博客  阅读(164)  评论(0编辑  收藏  举报

异步函数回调:首先加载文件,1.js加载完并执行完里面的代码,再执行回调函数里的代码

 1 function loadJS(src, callback){
 2     var script = document.createElement('script');
 3     var head = document.getElementsByTagName('head')[0];
 4     var loaded;
 5     script.src = src;
 6     if(typeof callback === 'function'){
 7         console.log(typeof callback === 'function')
 8         script.onload = script.onreadystatechange = function(){
 9             if(!loaded && (!script.readyState || /loaded|complete/.test(script.readyState))){
10                 script.onload = script.onreadystatechange = null;
11                 loaded = true;
12                 callback();
13             }
14         }
15     }
16     head.appendChild(script);
17 }
18 loadJS('1.js', function(){
19     alert('1.js已经加载完,到这里了')
20 })