javascript - JS window.onload 用法与文档

标签 javascript dom document-ready

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/

相关文章:

javascript - 根据 Angular 1.5 中的数组长度启用/禁用输入字段

jquery - 适用于 jQuery 的 Google AJAX 库 CDN

javascript - 简单关卡,选择DOM中的元素,优化,创建方法函数

Javascript 图像 src 没有改变

javascript - 函数不断重复运行 Jquery

javascript - 如何计算网站的页面加载时间,包括总时间而不仅仅是 document.ready() 时间?

javascript - 如何在 jquery 中创建一个 "reusable"函数?

Javascript在 Canvas 填充样式上绘制语音气泡仅更改文本颜色

javascript - amcharts 显示柱内的值

javascript - 检查时空对象返回 false