document.readyState用于基于gecko的浏览器

时间:2009-10-06 16:01:26

标签: javascript javascript-events gecko domready

IE在文档对象中具有属性readyState,表示当前状态,例如, “加载”,“完成”等。

有没有办法在基于Mozilla的浏览器中找到当前的文档加载状态? 我知道DOMContentLoaded事件,但它不适合我的情况,因为我的代码可以在此事件被触发后执行。

补充:不,我不能使用任何框架,也不要混淆XHR对象的.readyState属性。 它是一个书签,因此可以在任何加载阶段插入。

稍后补充:无论如何,对我来说这看起来不是什么大问题。因为这个属性will be added in FF3.6,并且当你操作未完成的DOM(unlike IE)时,它并没有在firefox中严重破坏。

2 个答案:

答案 0 :(得分:3)

不,这是不可能的。抱歉。但这就是你能做的。如果你在行动之前无法测试你想要的东西:

window.setTimeout(function () {
    // do your stuff here
}, 0);

(这肯定会在页面渲染后执行,但可能是在onload之后,而不是在DOMContentLoaded之后。)

如果你确实知道如何测试你正在寻找的东西:

(function () {
    if (/* test if what you're looking for is there */) {
        // do your stuff
    } else {
        window.setTimeout(arguments.callee, 0);
    }
})();

这将立即执行,除非你找不到任何东西,在这种情况下它会等到onload事件之后。

修改

Check out this solution.

它的作用是,在边缘情况下,检查document.getElementsByTagName(“*”)的最后一个元素是否未定义。这似乎对他有用,即使在Opera中也是如此。

答案 1 :(得分:2)

可以执行吗?只是收到DOM事件的通知并存储其状态。我不明白你的根本问题是什么。当然,你可以剔除这种方法的内涵,并根据你的情况进行调整。

jQuery的做法:

// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
    // Use the handy event callback
    document.addEventListener( "DOMContentLoaded", function(){
              //do stuff
    }, false );

// If IE event model is used
} else if ( document.attachEvent ) {
    // ensure firing before onload,
    // maybe late but safe also for iframes
    document.attachEvent("onreadystatechange", function(){
        if ( document.readyState === "complete" ) {
            document.detachEvent( "onreadystatechange", arguments.callee );
            jQuery.ready();
        }
    });

    // If IE and not an iframe
    // continually check to see if the document is ready
    if ( document.documentElement.doScroll && window == window.top ) (function(){
        if ( jQuery.isReady ) return;

        try {
            // If IE is used, use the trick by Diego Perini
            // http://javascript.nwbox.com/IEContentLoaded/
            document.documentElement.doScroll("left");
        } catch( error ) {
            setTimeout( arguments.callee, 0 );
            return;
        }

        // and execute any waiting functions
        jQuery.ready();
    })();
}

// A fallback to window.onload, that will always work
jQuery.event.add( window, "load", jQuery.ready );