自动加载jQuery的Javascript代码示例

当我们在Javascript里需要用到jQuery但又无法判断是否加载过时,可以通过下面的方法来自动判断并加载jQuery,代码如下:

function getScript(url, success) {
    var script = document.createElement('script');
    script.src = url;
    var head = document.getElementsByTagName('head')[0],
    done = false;
    
    // Attach handlers for all browsers
    script.onload = script.onreadystatechange = function() {
        if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
            done = true;
            
            // callback function provided as param
            success();
            
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
        };
    };
    head.appendChild(script);
};

if (typeof jQuery == 'undefined') {
    alert('Not found jQuery');
    getScript('http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', function() {
        alert('jQuery loaded');
    });
}

阳光部落原创,更多内容请访问http://www.sunbloger.com/

相关内容:

发表评论