问题
I want to call a function only if the document is still loading.. how can I?
回答1:
You could check document.readyState or use a simple variable in the global scope:
var ready = false;
$(document).ready(function () {
ready = true;
});
回答2:
You could run a function normally in JavaScript and overwrite it within jQuery.ready
:
function foo() {
// …
}
$(document).ready(function() {
foo = function() {};
});
foo();
Now if foo
calls itself recursively, it will stop when foo
is redefined when the document is ready.
回答3:
You could use the very useful jQuery deferred object to check if the document has/hasn't loaded yet:
http://api.jquery.com/category/deferred-object/
http://eng.wealthfront.com/2012/12/jquerydeferred-is-most-important-client.html
E.g.
(function($) {
var jqReady = $.Deferred();
// Bind doc ready to my deferred object
$(document).bind("ready", jqReady.resolve);
// Check to see is doc is ready
if(jqReady.state() !== 'resolved'){
alert('Doc is not ready');
}
$.when(jqReady).then(function () {
// Code here will run when doc is ready/state === 'resolved'
alert('Doc is ready');
});
})(jQuery);
jsFiddle example
来源:https://stackoverflow.com/questions/3028980/if-document-not-ready-how-can-i-check-if-the-page-is-still-loading-with-jq