我只想在文档仍在加载时调用一个函数。我该怎么做?
问问题
10119 次
3 回答
8
您可以在全局范围内检查document.readyState
或使用一个简单的变量:
var ready = false;
$(document).ready(function () {
ready = true;
});
于 2010-06-12T14:34:34.740 回答
0
您可以使用非常有用的 jQuery 延迟对象来检查文档是否已经/尚未加载:
http://api.jquery.com/category/deferred-object/
http://eng.wealthfront.com/2012/12/jquerydeferred-is-most-important-client.html
例如
(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);
于 2012-12-17T09:39:34.700 回答
0
您可以在 JavaScript 中正常运行一个函数并在其中覆盖它jQuery.ready
:
function foo() {
// …
}
$(document).ready(function() {
foo = function() {};
});
foo();
现在如果递归地调用自己,当文档准备好时foo
,它会在重新定义时停止。foo
于 2010-06-12T14:34:16.457 回答