簡體   English   中英

在另一個js文件中加載jQuery

[英]load jQuery in another js file

我有一個JavaScript文件,它也使用jQuery。 要加載它,我寫了這段代碼:

function include(filename)
{
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.src = filename;
    script.type = 'text/javascript';
    head.appendChild(script)
}

include('http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js');
alert("1");

$(document).read(function(){});
alert("2");

這會觸發alert("1") ,但第二次alert不起作用。 當我檢查元素時,我看到一個錯誤,表示未定義$

我該如何解決這個問題?

只有在加載腳本后才需要執行任何特定於jQuery的代碼,這顯然可能會在將其附加到head部分之后的稍后時間點發生:

function include(filename, onload) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.src = filename;
    script.type = 'text/javascript';
    script.onload = script.onreadystatechange = function() {
        if (script.readyState) {
            if (script.readyState === 'complete' || script.readyState === 'loaded') {
                script.onreadystatechange = null;                                                  
                onload();
            }
        } 
        else {
            onload();          
        }
    };
    head.appendChild(script);
}

include('http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js', function() {
    $(document).ready(function() {
        alert('the DOM is ready');
    });
});

這是一個現場演示

您還可以查看諸如yepnopeRequireJS之類的腳本加載器,這使得此任務更容易。

這里的問題可能是,即使您包含腳本,也不意味着當您嘗試執行$(document).ready(function(){});時它被加載$(document).ready(function(){}); 您可以查看Google Loader以防止出現此問題http://code.google.com/intl/fr-FR/apis/loader/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM