DOMContentLoaded有时可以工作,有时候并不会,而setTimeout通常总是可以工作
DOMContentLoaded有时可以工作,有时候并不会,而setTimeout通常总能工作。DOMContentLoaded有时可以工作,有时候并不会,而setTimeout通常总是可以工作
例如,下面的代码工作:
setTimeout(()=>{     let sites = ['mako.co.il']; 
    let regex = /\..+/; 
    let href = window.location.href; 
    for (let i = 0; i < sites.length; i++) { 
     if (href.includes(sites[i])) { 
      let domain = sites[i].replace(regex, ''); 
      document.body.innerHTML =` 
       <div style="direction: ltr; position: fixed; top: 0; z-index: 999999; display: block; width: 100%; height: 100%; background: red"> 
        <p style="position: relative; top: 40%; display: block; font-size: 66px; font-weight: bold; color: #fff; margin: 0 auto; text-align: center"> 
        Enough with this ${domain} bullshit! 
        </p> 
       </div> 
      `; 
     } 
    } 
}, 1500); 
但如果不是setTimeout(()=>{...}, 1500);我会用document.addEventListener('DOMContentLoaded',()=>{...});不会。
这是为什么?
在这两种情况下,我都会等待一段时间,然后执行代码。在所有的DOM树加载之后,代码会失败呢?
回答:
您的问题可能与某些嵌入式资源(如图像)有时从浏览器的缓存(快速)加载,有时从网络缓慢加载有关。如图像
的文件可DOMContentLoaded事件触发后document的,但前嵌入的资源被加载。
所以,你可能只需要window的load事件,而不是:
window.addEventListener('load', function() {     // This code runs after all resources including images are loaded. 
}, false); 
以上是 DOMContentLoaded有时可以工作,有时候并不会,而setTimeout通常总是可以工作 的全部内容, 来源链接: utcz.com/qa/257096.html








