To be as fast as possible, I will jump into the topic right now. I want to delay the script before jQuery is loaded.
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.in开发者_C百科sertBefore(s, x);
}
$(document).ready(function() {
//My code goes here, right?
});
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?
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);
}
}
Adapted from this post about loading jQuery with Greasemonkey scripts
you can use window.setInterval
to poll the status of 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
})();
Ahh, gotcha. That extra bit helped :)
What you want is for your code that depends on jQuery to execute when jQuery is loaded. To do this, we use the script's onload event, so:
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();
}
You may use native window.onload event which gets fired when the page is processed completely. All $.ready() functions will get called before it: https://developer.mozilla.org/en/DOM/window.onload
Note that there can only be one window.onload function. So you might have to take care for it. i.e. call it before calling your code.
More info: window.onload vs $(document).ready()
Especially the comments on Piskvor's posts are quite helpful.
精彩评论