【问题标题】:if $(document).not-ready()? How can I check if the page is still loading with Jquery?如果 $(document).not-ready()?如何检查页面是否仍在使用 Jquery 加载?
【发布时间】:2012-12-17 17:39:34
【问题描述】:

我只想在文档仍在加载时调用一个函数。我该怎么做?

【问题讨论】:

  • 当我看到这些问题时,我的问题是,你为什么不把你的代码放在$().ready() 中。我想那是因为你想在文档还没准备好的时候做点什么?

标签: jquery document-ready


【解决方案1】:

您可以检查document.readyState 或在全局范围内使用一个简单的变量:

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

【讨论】:

    【解决方案2】:

    您可以在 JavaScript 中正常运行函数并在 jQuery.ready 中覆盖它:

    function foo() {
        // …
    }
    $(document).ready(function() {
        foo = function() {};
    });
    foo();
    

    现在如果foo 递归调用自身,当文档准备好时重新定义foo 时它将停止。

    【讨论】:

    • 为什么不使用简单的变量而不是递归方法?
    【解决方案3】:

    您可以使用非常有用的 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);​
    

    jsFiddle example

    【讨论】:

    • 在 Chrome 65 中,页面在第一个警报之后加载并且从不显示 alert('Doc is ready')
    • @Dshiz 我刚刚在 Chrome 65 中测试了 JSFiddle 链接,它工作正常吗?
    • @Dshiz 一定是有其他问题。如果您与前任搭讪,很乐意为您提供帮助。
    猜你喜欢
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多