如何检测 DOMContentLoaded 是否被触发 [英] How to detect if DOMContentLoaded was fired

查看:37
本文介绍了如何检测 DOMContentLoaded 是否被触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试帮助开发一个库,为此我正在尝试处理页面加载.
在这个过程中我想让库完全兼容defer和async的使用.

I'm trying to help developing a library and for it I'm trying to work with page loading.
In the process I want to make the library completely compatible with the use of defer and async.

我想要的很简单:
我怎么知道 DOMContentLoaded 在文件执行时被触发了?

What I want is simple:
How can I know that DOMContentLoaded was fired by the time the file is executed?

为什么这么难?
在 IE 中,document.readyState 在 DOMContentLoaded 之前显示交互.
不会以任何方式使用浏览器检测,这违反了我和其他参与者的政策.

Why is this so difficult?
In IE, document.readyState show interactive before DOMContentLoaded.
I won't use browser detection in any way, it's against the policy of me and the rest of the participants.

正确的选择是什么?

好像我说的不够清楚.我想知道加载事件是否已经发生!!!我已经知道如何解决这个问题了!我想知道如何用DOMContentLoaded解决!!!

Seems like I wasn't clear enough. I'm not interested to know if the load event has already occurred!!! I already knew how to solve that problem! I want to know how to solve with DOMContentLoaded!!!

推荐答案

查看页面中的所有资源是否都已加载:

For seeing if all resources in the page have been loaded:

if (document.readyState === "complete" || document.readyState === "loaded") {
     // document is already ready to go
}

IE 和 webkit 已经支持了很长时间.它是在 3.6 中添加到 Firefox 中的.这是规范."loaded" 适用于较旧的 Safari 浏览器.

This has been supported in IE and webkit for a long time. It was added to Firefox in 3.6. Here's the spec. "loaded" is for older Safari browsers.

如果您想知道页面何时被加载和解析,但所有子资源尚未加载(这更类似于 DOMContentLoaded),您可以添加interactive"值:

If you want to know when the page has been loaded and parsed, but all subresources have not yet been loaded (which is more akin to DOMContentLoaded), you can add the "interactive" value:

if (document.readyState === "complete" 
     || document.readyState === "loaded" 
     || document.readyState === "interactive") {
     // document has at least been parsed
}

除此之外,如果您真的只想知道 DOMContentLoaded 何时触发,那么您必须为此安装一个事件处理程序(在它触发之前)并在它触发时设置一个标志.

Beyond this, if you really just want to know when DOMContentLoaded has fired, then you'll have to install an event handler for that (before it fires) and set a flag when it fires.

这个 MDN 文档也是一个非常好的阅读了解有关 DOM 状态的更多信息.

This MDN documentation is also a really good read about understanding more about the DOM states.

这篇关于如何检测 DOMContentLoaded 是否被触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆