jQuery加载比应该使用它的其他脚本慢

时间:2011-09-03 22:30:17

标签: javascript jquery html loading dereference

我想知道,如何在jQuery加载后运行一些东西? jQuery是否有“我准备好了”事件?

首先在我的getls.js

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://example.com/setls.js';
document.getElementsByTagName('body')[0].appendChild(script);

然后在setls.js

if (typeof jQuery == 'undefined') {  
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js';
    document.getElementsByTagName('body')[0].appendChild(script);
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://example.com/ls.js';
document.getElementsByTagName('body')[0].appendChild(script);

ls.js

$("body").css("background-color", "green");

但是ls.js的加载速度比jquery快,并告诉我Uncaught ReferenceError: $ is not defined。我该如何处理这个事件?谢谢你的帮助。

编辑:这是因为这个脚本会像谷歌分析一样,你知道。让用户只使用一行脚本并在他的代码中加载getls.js,会让他开心(哦,很酷,只有4行?有需要)。但我也必须检查jQuery,因为我稍后会使用jQuery,如果已经得到它,我无法再次加载它。在此之后我想用它。
所以不是关于document.ready事件,在我开始加载jQuery之前文档就已经准备好了。

5 个答案:

答案 0 :(得分:2)

让JQuery使用$.getScript()

加载你的ls.js,而不是竞争条件
$.getScript('http://example.com/ls.js', function(data, textStatus){
   console.log(data); //data returned
   console.log(textStatus); //success
   console.log('Load was performed.');
});

http://api.jquery.com/jQuery.getScript/

答案 1 :(得分:2)

您想要动态加载这两个脚本。您有两种选择:

  1. 在您要注入的脚本上使用onload。它在所有主流浏览器上都受支持,但在IE上进行测试,因为它几年前在IE上没有运行。这是一个干净的解决方案。
  2. 使用typeof(window.jQuery)使用计时器轮询jQuery变量的存在。定义它时,应该加载jQuery。

答案 2 :(得分:1)

检查循环,直到jQuery可用:

//Have to wait until jQuery will arrive
function wait_for_jQuery(){
    if (typeof jQuery == 'undefined'){
        setTimeout(wait_for_jQuery, 50);
    }else{
        $(document).ready(main()); 
    }
}
wait_for_jQuery();

function main(){ ... };

答案 3 :(得分:0)

将您的代码包装成:

$(document).ready(function(){

//your code

}

等待DOM和所有脚本和css文件加载。并确保在你的javascript文件之前添加了的jquery标记。

答案 4 :(得分:0)

jQuery有一个“我准备好了”的事件。您要做的是将代码包装在:

$(document).ready(function() {
    // Your code here
});

这将延迟文档内部代码的执行,直到完全加载DOM和jQuery。此外,将所有脚本标记放在页面底部是提高效率的好方法。