gpt4 book ai didi

javascript - JS window.onload 用法与文档

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:29:59 25 4
gpt4 key购买 nike

window.onload 从我的阅读中听起来它可以与 document.onload 松散地互换,但我的经验表明这是不正确的。我继承了一个 JS 脚本,但我不确定如何更正它。我希望 JS 在加载 DOM 后执行,而不是在加载所有资源后执行。我该怎么做?

目前我有:

window.onload = initDropMenu;

我试过:

 document.onload = initDropMenu;

这只会导致菜单无法加载。我也试过从 JS 中完全删除该行,并让 DOM 通过以下方式执行它:

<body onload="initDropMenu()">

这也导致没有菜单,并且控制台中没有错误。我的 JS 知识有限,我在这里缺少什么?

最佳答案

在窗口加载事件:

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>

在 HTML 元素上加载事件:

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()">

许多论坛甚至本站的某些答案可能会误导您,但是 load body 元素上的事件不仅等同于 load窗口上的事件,它是完全相同的事件。以下引用说明了这一点。

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]

DOMContentLoaded 事件:

开发者应该使用的是DOMContentLoaded文档上的事件。它会在 html 加载并完全解析后触发。

    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]

也许这是关于该主题的唯一具有适当引用的答案

关于javascript - JS window.onload 用法与文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49092746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com