如何暂停javascript直到完成某事?

为了尽可能快,我现在就会跳到这个话题。 我想在加载jQuery之前延迟脚本。

这是我的问题:我有代码在jQuery尚未加载时自动插入jQuery.js

 if(typeof jQuery=="undefined") { var s=document.createElement("script"); s.type="text/javascript"; s.async=true; s.src="http://code.jquery.com/jquery-1.5.1.min.js"; var x=document.getElementsByTagName("script")[0]; x.parentNode.insertBefore(s, x); } $(document).ready(function() { //My code goes here, right? }); 

它完美地插入脚本,但问题是$(document).ready()不会等到脚本完全加载,它会在加载脚本时立即跳转。 我想暂停,我该怎么办?

就像评论中提到的cwolves一样,这应该不是问题 – $(document).ready()应该只在加载jQuery时起作用。

但是,如果你发现你确实需要等到它被加载,你可能会这样:

 if(typeof jQuery=="undefined") { var s=document.createElement("script"); s.type="text/javascript"; s.async=true; s.src="http://code.jquery.com/jquery-1.5.1.min.js"; var x=document.getElementsByTagName("script")[0]; x.parentNode.insertBefore(s, x); wait(); } //... function wait() { if(typeof jQuery=="undefined") { setTimeout(wait, 200); } else { //jQuery is loaded, do what you need to $(document).ready(docLoaded); } } 

改编自这篇关于使用Greasemonkey脚本加载jQuery的post

你可以使用window.setInterval来轮询jQuery的状态:

 (function() { function main() { // code to continue with } function jQueryLoaded() { // test jQuery status here } var handle = window.setInterval( function() { if ( jQueryLoaded() ) { window.clearInterval(handle) main() } }, 1000 ); // 1000 msec interval })(); 

啊,有问题。 额外的一点帮助:)

你想要的是你的代码依赖于jQuery在加载jQuery时执行。 为此,我们使用脚本的onload事件,因此:

 function toBeExecuted(){ // code goes here } if(!jQuery){ var s = document.createElement("script"); s.type = "text/javascript"; s.src = "http://code.jquery.com/jquery-1.5.1.min.js"; s.onload = toBeExecuted; // because IE just HAS to be different s.onreadystatechange = function () { if(s.readyState == 'loaded' || s.readyState == 'complete'){ toBeExecuted(); } } var x = document.getElementsByTagName("script")[0]; document.getElementsByTagName('HEAD')[0].appendChild(s); }else{ toBeExecuted(); } 

您可以使用本机window.onload事件,该事件在完全处理页面时被触发。 所有$ .ready()函数都将在它之前被调用: https : //developer.mozilla.org/en/DOM/window.onload

请注意,只能有一个window.onload函数。 所以你可能需要照顾它。 即在调用代码之前调用它。

更多信息: window.onload vs $(document).ready()

特别是对Piskvorpost的评论非常有帮助。