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

筅森魡賤 提交于 2019-12-23 22:34:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!