检查脚本是否已加载。如果没有,请异步加载它

时间:2011-12-11 06:40:50

标签: javascript asynchronous

我正在尝试异步加载jQuery JS然后我想在完全加载时调用一些回调方法。 我可能一遍又一遍地使用相同的代码块。所以我想在实际添加之前检查是否已经添加了jQuery(或任何其他脚本)。如果它已经加载/加载,那么当前调用的回调应该附加到前一次调用的回调。这就是我想要做的。

/*BP Asynchronous JavaScript Loader*/
if (typeof bp_onload_queue == 'undefined') var bp_onload_queue = [];

if (typeof bp_dom_loaded == 'boolean') bp_dom_loaded = false;
else var bp_dom_loaded = false;

if (typeof bp_async_loader != 'function') {
    function bp_async_loader(src, callback, id) {

        var script = document.createElement('script');
        script.type = "text/javascript";
        script.async = true;
        script.src = src;
        script.id = id;
        //Check if script previously loaded.
        var previous_script = document.getElementById(id);
        if (previous_script) if (previous_script.readyState == "loaded" || previous_script.readyState == "complete") {
            callback();
            alert("had already loaded the same script completely");
            return;
        } else {

            script = previous_script;
        }
        if (script.onload != null) previous_callback = script.onload;
        script.onload = script.onreadystatechange = function() {
            var newcallback;
            if (previous_script && previous_callback) newcallback = function() {
                previous_callback();
                callback();
            };
            else newcallback = callback;
            if (bp_dom_loaded) {
                newcallback();
            } else bp_onload_queue.push(newcallback);
            // clean up for IE and Opera
            script.onload = null;
            script.onreadystatechange = null;
        };
        var head = document.getElementsByTagName('head')[0];
        if (!previous_script) head.appendChild(script);
        else alert("had already started loading that script but not complete.so we appended to the previous script's callback");

    }
}

if (typeof bp_domLoaded != 'function') function bp_domLoaded(callback) {
    bp_dom_loaded = true;
    var len = bp_onload_queue.length;
    for (var i = 0; i < len; i++) {
        bp_onload_queue[i]();
    }
} 
/*JS gets loaded here */

bp_domLoaded();

/*Loading jQuery Asynchronously */
bp_async_loader("http://code.jquery.com/jquery-1.4.4.js", function() {
    alert("script has been loaded : 1");
}, "jQueryjs");

bp_async_loader("http://code.jquery.com/jquery-1.4.4.js", function() {
    alert("script has been loaded : 2");
}, "jQueryjs");

有人可以告诉我这段代码是否有任何错误,或者有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

我正在寻找类似的东西并找到了这个 http://themergency.com/an-alternative-to-jquerys-getscript-function/