We have a JavaScript/JQuery page with a number of "initialization functions" a la:
$(function(){
//Do stuff
}
Is there a programmatic way y开发者_JAVA百科ou can determine when all these methods have completed running?
We could set a boolean variable to true in the last function()... was wondering if there was a more elegant way.
??
If you just need to determine if they have run, use $.isReady
, it'll be true when the DOM's ready to go, it's not set until just before executing all the handlers...so the pretty-much-being-single-threaded-ness would work you you there.
If you want to queue something to execute (it must be queued before document.ready
fires), bind it to "ready"
, like this:
$(document).bind("ready", function() { alert("All ready functions ran"); });
You can see how it's fired here, note that this is not the same as $(document).ready()
, which is another function.
Assuming all your initialisation "stuff" is synchronous, you can call a function at the end of the last one on your page, in which you can execute code in the knowledge that everything has been initialised.
$(function(){
//Do stuff
run();
}
function run() {
// we are initialised now...
}
While this isn't exactly what you asked for, it removes the need for checking that the initialisation functions have completed running... as soon as they have the run
function will be called.
try this (example):
HTML:
<div id="test"></div>
JS:
(function ($) {
var
owReady = $.ready,
readyEndList = [];
$.ready = function () {
var
toEnd = owReady(),
fn, i = 0;
if (toEnd)
return toEnd;
if (!$.isReady)
return toEnd;
while ( (fn = readyEndList[ i++ ]) ) {
fn.call( document, jQuery );
}
readyEndList = null;
return toEnd;
};
$.addToEndReady = function(fn) {
if ($.isFunction(fn))
readyEndList.push(fn);
};
$(function (ev) {
$('#test').append('<span>0</span><br />');
$.addToEndReady(function(){
$('#test').append('<span>end</span><br />');
});
});
// inicio del modulo
$(function (ev) {
$('#test').append('<span>1</span><br />');
});
$(function (ev) {
$('#test').append('<span>2</span><br />');
});
} (jQuery));
精彩评论