问题描述
window.onload
听起来像是可以与 document.onload
松散地互换,但我的经验表明这是不正确的。我继承了一个JS脚本,我不知道如何纠正它。我想要在DOM加载后执行JS,而不是在加载所有资源之后执行。我该怎么做?
window.onload
from my reading sounds like it is loosely interchangeable with document.onload
but my experience has shown this is incorrect. I've inherited a JS script and I'm not sure how to correct it. I want the JS to execute once the DOM has loaded, not once all resources have been loaded. How can I do this?
目前我有:
window.onload = initDropMenu;
我试过:
document.onload = initDropMenu;
这只会导致菜单无法加载。我也尝试从JS中完全删除该行,并让DOM通过以下方式执行:
which just results in the menu not loading. I've also tried removing the line altogether from the JS and just having the DOM execute it via:
<body onload="initDropMenu()">
这也导致没有菜单,并且控制台没有错误。我的JS知识有限,我在这里缺少什么?
that also resulted in no menu, and in no errors in the console. My JS knowledge is limited, what am I missing here?
推荐答案
在窗口加载事件:
<script>
window.onload = function(){ init(); };
</script>
在HTML元素上加载事件:
<!-- 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()">
许多论坛甚至网站上的一些答案都可能误导你,但是加载
body元素上的事件不仅仅等于 在窗口上加载
事件,它是完全相同事件即可。以下引用说明了这一点。
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.
DOMContentLoaded事件:
开发人员应该使用的是 DOMContentLoaded
文档上的事件。它在html加载并完全解析时触发。
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");
});
也许这是关于这个主题的唯一答案,它有适当的参考资料
这篇关于JS window.onload用法与文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!