简体   繁体   English

类似于“现代 HTML5”浏览器的 $(document).ready() Javascript

[英]Javascript like $(document).ready() for “modern HTML5” browsers

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() .我正在寻找一种经过验证的方法来绑定到准备好的文档,就像 jQuery 的$(document).ready() However, this is for a "modern browser only" page, with very light javascript, and I'd like to avoid loading jQuery here.但是,这是针对“仅限现代浏览器”的页面,使用非常轻的 javascript,我想避免在此处加载 jQuery。

Would someone kindly point me in the right direction?有人会指出我正确的方向吗?

Thanks!谢谢!

document.addEventListener('DOMContentLoaded', function () {
    /* ... */
});

The event "DOMContentLoaded" will be fired when the document has been parsed completely, that is without stylesheets* and additional images.当文档完全解析后,即没有样式表*和附加图像,将触发事件"DOMContentLoaded" If you need to wait for images and stylesheets, use "load" instead.如果您需要等待图像和样式表,请改用"load"

* only if the <script> is before the <link rel="stylesheet" ...> * 仅当<script><link rel="stylesheet" ...>

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 for some such cases also in all old browsers. window.onload = function() {}是很久以前的标准,而它也等待所有图像加载,它基本上是所有旧浏览器中某些此类情况的有效替代方法。 A user usually still should wait a second till he makes a responsible action.用户通常仍然应该等待一秒钟,直到他做出负责任的行动。

Edit : In my case, I needed it for all the libraries being loaded prior to anything else, as they were listed fixed in the footer (jquery).编辑:在我的情况下,我需要它用于在其他任何东西之前加载的所有库,因为它们在页脚(jquery)中固定列出。 At it is mine dependency to continue to work with is possible just once it is loaded.在我的依赖项中,只要加载它就可以继续使用。 So IMHO the fact that the user has to wait is irrelevant (unless I miss something here and am available to be explained), as it's the case with any way of jQuery loading, till it's not loaded it can't be worked with it.所以恕我直言,用户必须等待的事实是无关紧要的(除非我在这里遗漏了一些东西并且可以解释),因为任何 jQuery 加载方式都是如此,直到它没有加载它才能使用它。 For the sake of that point ofc any way there must be a backend check as client-side js can be "intercepted".为了这一点,任何方式都必须进行后端检查,因为客户端 js 可以被“拦截”。 Waiting for an entire document to load is certainly more lengthy than using it just after its inclusion, however this is for cases when you eg.等待整个文档加载肯定比在包含它之后使用它更长,但是这是针对以下情况的情况,例如。 can't affect the order of html scripts, eg when you use it in own 3rd party package.不能影响 html 脚本的顺序,例如当您在自己的 3rd 方包中使用它时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM