load jQuery from external source if not loaded

后端 未结 5 1513
臣服心动
臣服心动 2020-12-05 12:12

load jQuery from source

What I like to do is to drop my local jquery.js and have it hosted somewhere else. But what if Google is down? So let\'s cod

5条回答
  •  一向
    一向 (楼主)
    2020-12-05 12:56

    The problem with your script is that you're not waiting for the script to load before testing whether jQuery has been loaded. Use something like this instead:

    function loadScript(src, callback) {
        var head=document.getElementsByTagName('head')[0];
        var script= document.createElement('script');
        script.type= 'text/javascript';
        script.onreadystatechange = function () {
            if (this.readyState == 'complete' || this.readyState == 'loaded') {
                callback();
            }
        }
        script.onload = callback;
        script.src = src;
        head.appendChild(script);
    }
    
    function isjQueryLoaded() {
        return (typeof jQuery !== 'undefined');
    }
    
    function tryLoadChain() {
        var chain = arguments;
        if (!isjQueryLoaded()) {
            if (chain.length) {
                loadScript(
                    chain[0],
                    function() {
                        tryLoadChain.apply(this, Array.prototype.slice.call(chain, 1));
                    }
                );
            } else {
                alert('not loaded!');
            }
        } else {
            alert('loaded!');
        }
    }
    
    tryLoadChain(
        'https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js',
        'http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.4.min.js',
        'mine.js');
    

提交回复
热议问题