Javascript 像 $(document).ready() 用于“现代 HTML5”浏览器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15580084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript like $(document).ready() for "modern HTML5" browsers
提问by Randy Hall
This is most likely already a question somewhere, but I cannot find it, as EVERY single search turns up jQuery questions.
这很可能在某个地方已经是一个问题,但我找不到它,因为每次搜索都会出现 jQuery 问题。
I'm looking for a proven method to bind to the document being ready, much like jQuery's $(document).ready()
. However, this is for a "modern browser only" page, with very light javascript, and I'd like to avoid loading jQuery here.
我正在寻找一种经过验证的方法来绑定到准备好的文档,就像 jQuery 的$(document).ready()
. 但是,这是针对“仅限现代浏览器”的页面,使用非常轻的 javascript,我想避免在此处加载 jQuery。
Would someone kindly point me in the right direction?
有人会指出我正确的方向吗?
Thanks!
谢谢!
回答by Zeta
document.addEventListener('DOMContentLoaded', function () {
/* ... */
});
The event "DOMContentLoaded"
will be fired when the document has been parsed completely, that is without stylesheets* and additional images. If you need to wait for images and stylesheets, use "load"
instead.
该事件"DOMContentLoaded"
将在文档完全解析后触发,即没有样式表*和附加图像。如果您需要等待图像和样式表,请"load"
改用。
* only if the <script>
is before the <link rel="stylesheet" ...>
* 仅当在<script>
之前<link rel="stylesheet" ...>
回答by FentomX1
window.onload = function() {}
is a standard from the long past ago, whereas it also waits for all the images to load, it is basically a working, functional alternative also in all old browsers, and usually a user can wait a second to work with a website and it is usually also the case, that user still waits at least a second till he stars to work with the app anyway.
window.onload = function() {}
是很久以前的标准,虽然它也等待所有图像加载,但它基本上是所有旧浏览器中的一个有效的、功能性的替代方案,通常用户可以等待一秒钟来使用网站,它是通常也是如此,该用户仍然至少等待一秒钟,直到他开始使用该应用程序。
PS:Take the accepted delay with a grain of salt, but this is also one of the alternatives, as mentioned also in @Zeta 's comment Apr 17 '14 at 5:49 , but let's be honest, who reads all the answers sometimes, let alone all the comments.
PS:接受可接受的延迟,但这也是一种选择,正如@Zeta 在 2014 年 4 月 17 日 5:49 的@Zeta 评论中也提到的,但说实话,有时他会阅读所有答案,更不用说所有的评论了。