JS window.onload Usage Vs Document

左心房为你撑大大i 提交于 2019-12-04 14:32:27

Load Event on window:

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.
[source: developer.mozilla.org]

    <script>
       window.onload = function(){ init(); };
    </script>

Load Event on HTML Elements:

The load event is fired when a resource and its dependent resources have finished loading.
[source: developer.mozilla.org]

    <!-- When the image is loaded completely -->
    <img onload="image_loaded()" src="w3javascript.gif">

    <!-- When the frame is loaded completely (including all resources) -->
    <iframe onload="frame_loaded()" src="about.html">

    <!-- When body loaded completely (including all resources, images and iframes) -->
    <body onload="init()">

Many forums even some answers in this site may mislead you, but the load event on body element is not only just equivalent to load event on window, it is the exact same event. The following quote clarifies it.

For historical reasons, some attributes/properties on the <body> and <frameset> elements actually set event handlers on their parent Window object. (The HTML specification names these: onblur, onerror, onfocus, onload, onscroll.)
[source: developer.mozilla.org]

The DOMContentLoaded Event:

What developers should use is DOMContentLoaded event on document. It fires when the html has loaded and parsed completely.

    document.addEventListener("DOMContentLoaded", function(event) {
        alert("Document is ready");
    });

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.
[source: developer.mozilla.org]

Perhaps this is the only answer regarding this topic that has proper References

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