javascript 在另一个 js 文件中加载 jQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8139794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:26:13  来源:igfitidea点击:

load jQuery in another js file

javascriptjquery

提问by Moein Hosseini

I have a JavaScript file, which also uses jQuery in it too. To load it, I wrote this code:

我有一个 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");

This fires alert("1"), but the second alertdoesn't work. When I inspect elements, I see an error which says that $in not defined.

这会触发alert("1"),但第二个alert不起作用。当我检查元素时,我看到一个错误,指出$未定义。

How should I solve this problem?

我应该如何解决这个问题?

回答by Darin Dimitrov

You need to execute any jQuery specific code only once the script is loaded which obviously might happen at a much later point in time after appending it to the head section:

您只需要在加载脚本后执行任何特定于 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');
    });
});

And here's a live demo.

这是一个现场演示

You may also take a look at script loaders such as yepnopeor RequireJSwhich make this task easier.

您还可以查看脚本加载器,例如yepnopeRequireJS,它们使此任务更容易。

回答by Leo

The problem here is probably that, even though you include the script, it doesn't mean it is loaded when you try to do $(document).ready(function(){});. You could look into Google Loader to prevent this problem http://code.google.com/intl/fr-FR/apis/loader/

这里的问题可能是,即使您包含脚本,也不意味着它在您尝试执行$(document).ready(function(){});. 您可以查看 Google Loader 以防止出现此问题http://code.google.com/intl/fr-FR/apis/loader/