简体   繁体   English

手动触发domContentLoaded

[英]Fire domContentLoaded manually

I'm stumble with a script that do this: 我偶然发现了一个执行此操作的脚本:

"complete" === document.readyState ? setTimeout(I, 1) : document.addEventListener ? (document.addEventListener("DOMContentLoaded", X, h), window.addEventListener("load", X, h)) : window.attachEvent ? window.attachEvent("onload", X) : console.log("No available event.")

where X and I are a functions, and h is false. 其中X和I是函数,h是假的。

What does it do? 它有什么作用?

Maybe you will understand it better this way: 也许你会这样更好地理解它:

if("complete" === document.readyState){
    setTimeout(I, 1);
}else{
    if(document.addEventListener){
        document.addEventListener("DOMContentLoaded", X, h),
        window.addEventListener("load", X, h));
    }else{
        if(window.attachEvent){
            window.attachEvent("onload", X);
        }else{
            console.log("No available event.");
        }
    }
}

It does: 它确实:

  1. Checks if the document is loaded 检查文档是否已加载
  2. If it is, function I is called after 1 ms 如果是,则在1 ms后调用函数I
  3. If not, it checks if browser supports addEventListener 如果没有,它会检查浏览器是否支持addEventListener
  4. If it is supported, when the DOM is loaded, function X will be called (through DOMContentLoaded or load events) 如果它被支持,当加载DOM时,将调用函数X (通过DOMContentLoadedload事件)
  5. If it isn't, it checks if browser supports attachEvent 如果不是,则检查浏览器是否支持attachEvent
  6. If it is supported, when the DOM is loaded, function X will be called (through load event) 如果支持,则在加载DOM时,将调用函数X(通过load事件)
  7. If it isn't, it says that the browser doesn't support addEventListener nor attachEvent 如果不是,则表示浏览器不支持addEventListenerattachEvent

I guess function X accesses or modifies the DOM, so the script above checks if the DOM is completely loaded before calling X . 我猜函数X访问或修改DOM,因此上面的脚本在调用X之前检查DOM是否已完全加载。

That appears to be a chunk of code that detects the loaded state of the DOM in a cross-browser fashion. 这似乎是一个代码块,以跨浏览器的方式检测DOM的加载状态。

If the browser does not support DOMContentLoaded, it falls back to using the window load event. 如果浏览器不支持DOMContentLoaded,则会回退到使用窗口加载事件。

This is used to initiate your code once the DOM is available to be manipulated, ie after the page has rendered. 一旦可以操作DOM,即在页面呈现之后,这用于启动代码。

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

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