简体   繁体   English

window.onload 与 document.onload

[英]window.onload vs document.onload

Which is more widely supported: window.onload or document.onload ?哪个得到更广泛的支持: window.onloaddocument.onload

When do they fire?他们什么时候开火?

window.onload

  • By default, it is fired when the entire page loads, including its content (images, CSS, scripts, etc.).默认情况下,它会在整个页面加载时触发,包括其内容(图像、CSS、脚本等)。

In some browsers it now takes over the role of document.onload and fires when the DOM is ready as well.在某些浏览器中,它现在接管了document.onload的角色,并在 DOM 准备就绪时触发。

document.onload

  • It is called when the DOM is ready which can be prior to images and other external content is loaded.当 DOM 准备好时调用它,这可以加载图像和其他外部内容之前。

How well are they supported?他们的支持程度如何?

window.onload appears to be the most widely supported. window.onload似乎是最广泛支持的。 In fact, some of the most modern browsers have in a sense replaced document.onload with window.onload .事实上,一些最现代的浏览器在某种意义上已经将document.onload替换为window.onload

Browser support issues are most likely the reason why many people are starting to use libraries such as jQuery to handle the checking for the document being ready, like so:浏览器支持问题很可能是许多人开始使用诸如jQuery之类的库来处理文档准备就绪检查的原因,如下所示:

$(document).ready(function() { /* code here */ });
$(function() { /* code here */ });

For the purpose of history.为了历史的目的。 window.onload vs body.onload : window.onloadbody.onload

A similar question was asked on codingforums a while back regarding the usage of window.onload over body.onload .关于window.onload而不是body.onload的使用, window.onload在 codingforums 上提出了一个类似的问题。 The result seemed to be that you should use window.onload because it is good to separate your structure from the action.结果似乎是您应该使用window.onload因为将您的结构与动作分开是很好的。

The general idea is that window.onload fires when the document's window is ready for presentation and document.onload fires when the DOM tree (built from the markup code within the document) is completed .一般的想法是window.onload在文档的 window准备好呈现触发,并且 document.onloadDOM 树(由文档中的标记代码构建)完成时触发。

Ideally, subscribing to DOM-tree events , allows offscreen-manipulations through Javascript, incurring almost no CPU load .理想情况下,订阅DOM 树事件,允许通过 Javascript 进行屏幕外操作,几乎不会产生 CPU 负载 Contrarily, window.onload can take a while to fire , when multiple external resources have yet to be requested, parsed and loaded.相反,当尚未请求、解析和加载多个外部资源时, window.onload可能需要一段时间才能触发

►Test scenario: ►测试场景:

To observe the difference and how your browser of choice implements the aforementioned event handlers , simply insert the following code within your document's - <body> - tag.要观察差异以及您选择的浏览器如何实现上述事件处理程序,只需在文档的 - <body> - 标记中插入以下代码。

<script language="javascript">
window.tdiff = []; fred = function(a,b){return a-b;};
window.document.onload = function(e){ 
    console.log("document.onload", e, Date.now() ,window.tdiff,  
    (window.tdiff[0] = Date.now()) && window.tdiff.reduce(fred) ); 
}
window.onload = function(e){ 
    console.log("window.onload", e, Date.now() ,window.tdiff, 
    (window.tdiff[1] = Date.now()) && window.tdiff.reduce(fred) ); 
}
</script>

►Result: ►结果:

Here is the resulting behavior, observable for Chrome v20 (and probably most current browsers).这是 Chrome v20(可能是大多数当前浏览器)可观察到的结果行为。

  • No document.onload event.没有document.onload事件。
  • onload fires twice when declared inside the <body> , once when declared inside the <head> (where the event then acts as document.onload ). onload<body>中声明时触发两次,在<head>中声明时触发一次(然后该事件充当document.onload )。
  • counting and acting dependent on the state of the counter allows to emulate both event behaviors.计数和操作取决于计数器的 state 允许模拟两种事件行为。
  • Alternatively declare the window.onload event handler within the confines of the HTML- <head> element.或者,在 HTML- <head>元素的范围内声明window.onload事件处理程序。

►Example Project: ►示例项目:

The code above is taken from this project's codebase ( index.html and keyboarder.js ).上面的代码取自该项目的代码库( index.htmlkeyboarder.js )。


For a list of event handlers of the window object , please refer to the MDN documentation.有关window object 的事件处理程序列表,请参阅 MDN 文档。

Add Event Listener添加事件监听器

<script type="text/javascript">
  document.addEventListener("DOMContentLoaded", function(event) {
      /* 
        - Code to execute when only the HTML document is loaded.
        - This doesn't wait for stylesheets, 
          images, and subframes to finish loading. 
      */
  });
</script>

Update March 2017

1 Vanilla JavaScript 1 香草 JavaScript

window.addEventListener('load', function() {
    console.log('All assets are loaded')
})

2 jQuery 2 jQuery

$(window).on('load', function() {
    console.log('All assets are loaded')
})

Good Luck. 祝你好运。

According to Parsing HTML documents - The end ,根据解析 HTML 文件 - 结束

  1. The browser parses the HTML source and runs deferred scripts.浏览器解析 HTML 源并运行延迟脚本。

  2. A DOMContentLoaded is dispatched at the document when all the HTML has been parsed and have run.当所有 HTML 已被解析并运行时,将在document中调度DOMContentLoaded The event bubbles to the window .事件冒泡到window

  3. The browser loads resources (like images) that delay the load event.浏览器加载延迟加载事件的资源(如图像)。

  4. A load event is dispatched at the window .window处调度load事件。

Therefore, the order of execution will be因此,执行顺序将是

  1. DOMContentLoaded event listeners of window in the capture phase window在捕获阶段的DOMContentLoaded事件监听器
  2. DOMContentLoaded event listeners of document documentDOMContentLoaded事件监听器
  3. DOMContentLoaded event listeners of window in the bubble phase冒泡阶段windowDOMContentLoaded事件监听器
  4. load event listeners (including onload event handler) of window load window的事件监听器(包括onload事件处理程序)

A bubble load event listener (including onload event handler) in document should never be invoked.永远不应调用document中的气泡load事件侦听器(包括onload事件处理程序)。 Only capture load listeners might be invoked, but due to the load of a sub-resource like a stylesheet, not due to the load of the document itself.只有捕获load侦听器可能会被调用,但是由于像样式表这样的子资源的负载,而不是由于文档本身的负载。

 window.addEventListener('DOMContentLoaded', function() { console.log('window - DOMContentLoaded - capture'); // 1st }, true); document.addEventListener('DOMContentLoaded', function() { console.log('document - DOMContentLoaded - capture'); // 2nd }, true); document.addEventListener('DOMContentLoaded', function() { console.log('document - DOMContentLoaded - bubble'); // 2nd }); window.addEventListener('DOMContentLoaded', function() { console.log('window - DOMContentLoaded - bubble'); // 3rd }); window.addEventListener('load', function() { console.log('window - load - capture'); // 4th }, true); document.addEventListener('load', function(e) { /* Filter out load events not related to the document */ if(['style','script'].indexOf(e.target.tagName.toLowerCase()) < 0) console.log('document - load - capture'); // DOES NOT HAPPEN }, true); document.addEventListener('load', function() { console.log('document - load - bubble'); // DOES NOT HAPPEN }); window.addEventListener('load', function() { console.log('window - load - bubble'); // 4th }); window.onload = function() { console.log('window - onload'); // 4th }; document.onload = function() { console.log('document - onload'); // DOES NOT HAPPEN };

In Chrome, window.onload is different from <body onload=""> , whereas they are the same in both Firefox(version 35.0) and IE (version 11).在 Chrome 中,window.onload 与<body onload="">不同,而在 Firefox(35.0 版)和 IE(11 版)中它们是相同的。

You could explore that by the following snippet:您可以通过以下代码段进行探索:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <!--import css here-->
        <!--import js scripts here-->

        <script language="javascript">

            function bodyOnloadHandler() {
                console.log("body onload");
            }

            window.onload = function(e) {
                console.log("window loaded");
            };
        </script>
    </head>

    <body onload="bodyOnloadHandler()">

        Page contents go here.

    </body>
</html>

And you will see both "window loaded"(which comes firstly) and "body onload" in Chrome console.您将在 Chrome 控制台中看到“加载窗口”(首先出现)和“加载正文”。 However, you will see just "body onload" in Firefox and IE.但是,您只会在 Firefox 和 IE 中看到“body onload”。 If you run " window.onload.toString() " in the consoles of IE & FF, you will see:如果您在 IE & FF 的控制台中运行“ window.onload.toString() ”,您将看到:

"function onload(event) { bodyOnloadHandler() }" “函数加载(事件){bodyOnloadHandler()}”

which means that the assignment "window.onload = function(e)..." is overwritten.这意味着赋值“window.onload = function(e)...”被覆盖。

window.onload and onunload are shortcuts to document.body.onload and document.body.onunload window.onloadonunloaddocument.body.onloaddocument.body.onunload的快捷方式

document.onload and onload handler on all html tag seems to be reserved however never triggered所有 html 标签上的document.onloadonload处理程序似乎被保留,但从未触发

' onload ' in document -> true文档中的“ onload ”-> true

window.onload however they are often the same thing. window.onload 但是它们通常是相同的。 Similarly body.onload becomes window.onload in IE.同样 body.onload 在 IE 中变为 window.onload。

Window.onload is the standard, however - the web browser in the PS3 (based on Netfront) doesn't support the window object, so you can't use it there. Window.onload is the standard, however - the web browser in the PS3 (based on Netfront) doesn't support the window object, so you can't use it there.

In short简而言之

  • window.onload is not supported by IE 6-8IE 6-8 不支持window.onload
  • document.onload is not supported by any modern browser (event is never fired)任何现代浏览器都不支持document.onload (从不触发事件)

 window.onload = () => console.log('window.onload works'); // fired document.onload = () => console.log('document.onload works'); // not fired

document.load is undefined. document.load未定义。 So what are you guys talking about?那你们在说什么?

Event with document.addEventListener('load',cbFunc) , the cbFunc will NEVER be triggered.带有document.addEventListener('load',cbFunc)的事件, cbFunc永远不会被触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM