是否有不使用框架的 window.onload 的通用替代方案?
在上一个问题中 我了解到 JavaScript 中存在一个与在 DOMReady 事件触发之前在 BODY 元素上使用appendChild 相关的错误。
我可以通过将代码包装在 window.onload 事件中来解决此问题。阅读本文后,我了解到 window.onload 仅支持单个侦听器,并且我不能保证我不会破坏其他人的侦听器,也不能保证其他人的侦听器不会破坏我的侦听器。
查看 $(document).ready(function(){}); 的源代码,我意识到该语法的简单性可能涉及很多内容。
有没有一种通用的方法可以让我在不使用 jQuery 或其他 JS 库的情况下等待 DOMReady 事件?虽然这似乎可以解决问题,但我不希望对第三方库有任何依赖,以便我的代码正常工作。
In a previous question I learned of a bug in my JavaScript related to using appendChild on the BODY element before the DOMReady event was fired.
I was able to resolve this by wrapping my code in a window.onload event. Reading up on this, I have learned that window.onload only supports a single listener, and I can't guarantee I am not clobbering someone else's listener or that someone else's listener is not clobbering mine.
Looking at the source for $(document).ready(function(){});
, I realize there is perhaps a lot that goes into the simplicity of that syntax.
Is there a universal way for me to wait for the DOMReady event without using jQuery or another JS library? While it seems like that would do the trick, I would prefer not to have any dependencies on a third party library in order for my code to work correctly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以执行以下操作:
将现有的
onload
包装在带有附加函数的新函数中。这取自 http://www.webreference.com/programming/javascript/onloads/< /a>但是,对于在文档准备好而不是在加载时执行此操作(不同的事情,加载是在下载所有内容时,而准备是在加载文档时)看看这个问题: <一href="https://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery">$(document).ready 相当于没有 jQuery
You can do something like:
which wraps the existing
onload
in a new function with an additional function. This is taken from http://www.webreference.com/programming/javascript/onloads/However, for doing it on document ready and not onload (different things, onload is when everything is downloaded where ready is when the document are loaded) look at this question: $(document).ready equivalent without jQuery
您可以使用:
您还可以将“onpageshow”替换为“onload”以获得更好的兼容性。
这也可能有帮助:
https://developer.mozilla.org/en/DOM/element.addEventListener
You can use:
You can also replace "onpageshow" with "onload" for better compatibility.
This may also be helpful:
https://developer.mozilla.org/en/DOM/element.addEventListener