在 jquery.ready 之后加载 javascript 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2829483/
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
loading javascript file after jquery.ready
提问by Kyle
I want to load a javascript file at the end of jquery.ready so that the code in my ready handler doesn't have to wait to execute until this large javascript file is loaded.
我想在 jquery.ready 的末尾加载一个 javascript 文件,这样我的就绪处理程序中的代码就不必等到加载这个大的 javascript 文件时才执行。
My jquery.ready code doesn't rely on this javascript file at all.
我的 jquery.ready 代码根本不依赖于这个 javascript 文件。
Would this be a good way to do that?
这会是一个很好的方法吗?
$(function(){
...
...
$('head').append('<script type="text/javascript" src="/largejs.js"></script>');
});
回答by Emil Vikstr?m
Use .getScript: http://api.jquery.com/jQuery.getScript/
使用 .getScript:http://api.jquery.com/jQuery.getScript/
$(document).ready(function(){
...
...
$.getScript("largejs.js");
});
回答by Shahadat Hossain Khan
solution will check jquery already loaded, if not it will check after some time here 500ms and loop until it found jquery
解决方案将检查 jquery 是否已加载,如果没有,它将在 500 毫秒后检查并循环直到找到 jquery
function loadScriptAfterJQueryReady(jsFile) {
setTimeout(function () {
var loadScript=true;
if (typeof jQuery == 'undefined') {
if (typeof window.jQuery == 'undefined') {
/* jQuery is not loaded */
loadScript=false;
loadScriptAfterJQueryReady(jsFile);
}else{
/* jQuery is loaded */
}
} else {
/* jQuery is loaded */
}
if(true==loadScript) jQuery.getScript(jsFile);
}, 500);
}
loadScriptAfterJQueryReady("my.js");
回答by Diodeus - James MacFarlane
The quoted "</script>" tag will actually end your block of JavaScript prematurely.
引用的 " </script>" 标签实际上会过早地结束您的 JavaScript 块。
I'd use this method:
我会使用这种方法:
var newScript = $(document.createElement('script'));
newScript.src="/largejs.js"
回答by David Droddy
If your application is new and not too far along yet, you could get a lot out of using LABjs for that purpose. It allows all your script files to load in parallel or, even, at any other time that you prefer (on demand). http://labjs.com/
如果您的应用程序是新的并且还不太远,那么为此目的使用 LABjs 可以获得很多好处。它允许您的所有脚本文件并行加载,甚至可以在您喜欢的任何其他时间(按需)加载。 http://labjs.com/

