开发者

if $(document).not-ready()? How can I check if the page is still loading with Jquery?

I want to call a function onl开发者_如何学JAVAy if the document is still loading.. how can I?


You could check document.readyState or use a simple variable in the global scope:

var ready = false;
$(document).ready(function () {
    ready = true;
});


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜