如何暂停javascript直到完成某件事? [英] How to pause javascript until something is done?
问题描述
为了尽快,我现在将跳至该主题. 我想在加载jQuery之前延迟脚本.
To be as fast as possible, I will jump into the topic right now. I want to delay the script before jQuery is loaded.
这是我的问题:我有一些代码,当尚未加载jQuery时会自动插入jQuery.js
:
Here is my problem: I have code which inserts jQuery.js
automatically when jQuery isn't loaded yet:
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()
不会等到脚本完全加载后,在加载脚本时会立即跳下.我想在那儿停顿,该怎么办?
It works perfectly to insert the script, but the problem is $(document).ready()
does not wait until the script is loaded completely, it jumps down immediately while the script is being loaded. I want to pause right there, what should I do?
推荐答案
就像注释中提到的狼一样,这应该不成问题-$(document).ready()
仅在加载jQuery时才起作用.
Like cwolves mentioned in the comment, this shouldn't be a problem - $(document).ready()
should only work when jQuery is loaded.
但是,如果发现要做需要等到加载完成,就可以这样:
However, if you find that you do need to wait until it's loaded, you could so something like this:
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
这篇关于如何暂停javascript直到完成某件事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!