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

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

问题描述

我正在尝试帮助开发一个图书馆,因此我正在尝试使用页面加载。

在此过程中,我想使图书馆完全兼容使用延迟和异步



我想要的很简单:

如何知道DOMContentLoaded在文件执行时被触发?



为什么这么难?

在IE中,document.readyState在DOMContentLoaded之前显示交互式。

不会以任何方式使用浏览器检测,这违反了我和其他参与者的政策。



有什么正确的选择?



编辑:



似乎我不够清楚。我很有兴趣知道加载事件是否已经发生!我已经知道如何解决这个问题!我想知道如何用DOMContentLoaded解决!!!

解决方案

我会认为你可以使用:

  if(document.readyState ===complete|| document.readyState ===loaded){
// document is已经准备好了
}

这在IE和webkit中已经很长时间了。它在3.6中添加到Firefox。以下是规格。 c code code code code code code code code code code code code code $ c $所有子资源尚未加载,您可以添加交互式值:

  if(document.readyState ===完成
|| document.readyState ===加载
|| document.readyState ===interactive){
//文档至少已被解析
}

除此之外,如果你真的只想知道DOMContentLoaded何时触发,那么你会有安装一个事件处理程序(在触发之前),并在触发时设置一个标志。



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


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.

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

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.

What's the correct alternative?

Edit:

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!!!

解决方案

I would think you could use:

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

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.

If you want to know when the page has been parsed, but all subresources have not yet been loaded, you can add the "interactive" value:

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

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.

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

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

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