JavaScript的窗口之间有什么区别。onload和jQuery的$(document).ready()方法?


当前回答

窗口。onload是由DOM api提供的,它说“加载事件在给定资源加载时触发”。

"加载事件在文档加载过程结束时触发。此时,文档中的所有对象都在DOM中,所有图像、脚本、链接和子帧都已完成加载。” DOM onload

但是在jQuery中,$(document).ready()只会在页面文档对象模型(DOM)准备好执行JavaScript代码时运行。这并不包括图像,脚本,iframes等jquery就绪事件

因此jquery ready方法将在dom onload事件之前运行。

其他回答

窗口。onload是由DOM api提供的,它说“加载事件在给定资源加载时触发”。

"加载事件在文档加载过程结束时触发。此时,文档中的所有对象都在DOM中,所有图像、脚本、链接和子帧都已完成加载。” DOM onload

但是在jQuery中,$(document).ready()只会在页面文档对象模型(DOM)准备好执行JavaScript代码时运行。这并不包括图像,脚本,iframes等jquery就绪事件

因此jquery ready方法将在dom onload事件之前运行。

$(document).ready()是一个jQuery事件,发生在HTML文档完全加载时,而窗口。Onload事件稍后发生,当页面上的所有内容(包括图像)都加载时。

窗口。onload是DOM中的一个纯javascript事件,而$(document).ready()事件是jQuery中的一个方法。

$(document).ready()通常是jQuery的包装器,以确保所有加载的元素都能在jQuery中使用…

看看jQuery源代码,了解它是如何工作的:

jQuery.ready.promise = function( obj ) {
    if ( !readyList ) {

        readyList = jQuery.Deferred();

        // Catch cases where $(document).ready() is called after the browser event has already occurred.
        // we once tried to use readyState "interactive" here, but it caused issues like the one
        // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
        if ( document.readyState === "complete" ) {
            // Handle it asynchronously to allow scripts the opportunity to delay ready
            setTimeout( jQuery.ready );

        // Standards-based browsers support DOMContentLoaded
        } else if ( document.addEventListener ) {
            // Use the handy event callback
            document.addEventListener( "DOMContentLoaded", completed, false );

            // A fallback to window.onload, that will always work
            window.addEventListener( "load", completed, false );

        // If IE event model is used
        } else {
            // Ensure firing before onload, maybe late but safe also for iframes
            document.attachEvent( "onreadystatechange", completed );

            // A fallback to window.onload, that will always work
            window.attachEvent( "onload", completed );

            // If IE and not a frame
            // continually check to see if the document is ready
            var top = false;

            try {
                top = window.frameElement == null && document.documentElement;
            } catch(e) {}

            if ( top && top.doScroll ) {
                (function doScrollCheck() {
                    if ( !jQuery.isReady ) {

                        try {
                            // Use the trick by Diego Perini
                            // http://javascript.nwbox.com/IEContentLoaded/
                            top.doScroll("left");
                        } catch(e) {
                            return setTimeout( doScrollCheck, 50 );
                        }

                        // detach all dom ready events
                        detach();

                        // and execute any waiting functions
                        jQuery.ready();
                    }
                })();
            }
        }
    }
    return readyList.promise( obj );
};
jQuery.fn.ready = function( fn ) {
    // Add the callback
    jQuery.ready.promise().done( fn );

    return this;
};

我还创建了下面的图像作为两者的快速参考:

事件

美元(文档)。on('ready', handler)绑定到来自jQuery的ready事件。加载DOM时调用处理程序。像图像这样的资产可能仍然缺失。如果文档在绑定时已经准备好,那么它将永远不会被调用。jQuery为此使用DOMContentLoaded-Event,如果不可用则模拟它。

美元(文档)。On ('load', handler)是一个事件,当所有资源从服务器加载时将被触发。图像现在已经加载。onload是一个原始HTML事件,而ready是由jQuery构建的。

功能

$(document).ready(handler)实际上是一个承诺。如果在调用时文档已经准备好,则处理程序将立即被调用。否则它会绑定到ready-Event。

在jQuery 1.8之前,$(document).load(handler)作为$(document).on('load',handler)的别名存在。

进一步的阅读

时机 在函数就绪时 一个例子 承诺 删除的事件别名

时间过得真快,现在是ECMAScript 2021年,人们越来越少使用IE11。相反,最多的两个事件是load和DOMContentLoaded。

DOMContentLoaded在初始HTML文档完全加载和解析后触发。

load在DOMContentLoaded和整个页面加载后触发, 等待所有相关资源完成加载。资源示例:脚本,样式表,图像和iframe等。

重点:同步脚本将暂停DOM的解析。

这两个事件都可以用来确定DOM是否可以使用。例子:

<script>
    // DOM hasn't been completely parsed
    document.body; // null

    window.addEventListener('DOMContentLoaded', () => {
        // Now safely manipulate DOM
        document.querySelector('#id');
        document.body.appendChild();
    });

    /**
     * Should be used only to detect a fully-loaded page.
     * 
     * If you just want to manipulate DOM safely, `DOMContentLoaded` is better.
     */
    window.addEventListener('load', () => {
        // Safely manipulate DOM too
        document.links;
    });
</script>

ready事件发生在HTML文档加载之后,而onload事件发生在稍后,当所有内容(例如图像)也已加载时。

onload事件是DOM中的标准事件,而ready事件是特定于jQuery的。ready事件的目的是,它应该在文档加载后尽可能早地发生,以便向页面中的元素添加功能的代码不必等待所有内容加载完毕。