日期:2014-05-16  浏览次数:20445 次

异步加载js文件并执行js方法:实现异步处理网页的复杂效果
var JSLoader = function(){
    
    var scripts = {}; // scripts['a.js'] = {loaded:false,funs:[]}
    
    function getScript(url){
        var script = scripts[url];
        if (!script){
            script = {loaded:false, funs:[]};
            scripts[url] = script;
            add(script, url);
        }
        return script;
    }
    
                
    function run(script){
        var funs = script.funs,
            len = funs.length,
            i = 0;
        
        for (; i<len; i++){
            var fun = funs.pop();
            fun();
        }
    }
    
    function add(script, url){
        var scriptdom = document.createElement('script');
        scriptdom.type = 'text/javascript';
        scriptdom.loaded = false;
        scriptdom.src = url;
        
        scriptdom.onload = function(){
            scriptdom.loaded = true;
            run(script);
            scriptdom.onload = scriptdom.onreadystatechange = null;
        };
        
        //for ie
        scriptdom.onreadystatechange = function(){
            if ((scriptdom.readyState === 'loaded' || 
                    scriptdom.readyState === 'complete') && !scriptdom.loaded) {
                
                run(script);
                scriptdom.onload = scriptdom.onreadystatechange = null;
            }
        };
        
        document.getElementsByTagName('head')[0].appendChild(scriptdom);
    }
    
    return {
        load: function(url){
            var arg = arguments,
                len = arg.length,
                i = 1,
                script = getScript(url),
                loaded = script.loaded;
            
            for (; i<len; i++){
                var fun = arg[i];
                if (typeof fun === 'function'){
                    if (loaded) {
                        fun();
                    }else{
                        script.funs.push(fun);
                    }
                }
            }
        }
    };
}();

?

调用方法示例:

先在页面上加载JSLoader.js文件

然后执行

?JSLoader.load('js/test.js' , function () {a();})

表示异步加载test.js文件,并且加载完成后再执行a()方法,a()方法是test.js里面的方法,a()方法就是负责渲染一些前端页面的网页效果来的。

不过该方法在ie7下并不会产生异步的效果,在ie7下需要使用延时触发器来包装一下,如:

setTimeout(" JSLoader.load('js/test.js' , function () {a();})", 1);