2017-11-25 442 views
0

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樹加載之後,代碼會失敗呢?

+1

‘有時的確,有時不工作’ - 你能解釋一下?給我們一些更具體的情景,以瞭解什麼時候做什麼和什麼時候不起作用。例如:「DOMContentLoaded事件僅適用於初始頁面加載,而不適用於網站內的連續導航。」這有助於我們縮小問題的範圍。 – SidOfc

+1

[內部代碼DOMContentLoaded事件不工作]的可能重複(https://stackoverflow.com/questions/39993676/code-inside-domcontentloaded-event-not-working)|另外這個評論:https://stackoverflow.com/questions/39993676/code-inside-domcontentloaded-event-not-working#comment67265322_39993676 – yuriy636

+0

可悲的是我真的認爲我不能,在這種情況下,@SidOfc,因爲如果我沒有記錯大約2個月前它工作,現在它沒有。我希望我有更多的細節,在這個...上:|我可能會錯誤地回憶起來,'DOMContentLoaded'完全不起作用。 – Arcticooling

回答

1

您的問題可能與某些嵌入式資源(如圖像)有時從瀏覽器的緩存(快速)加載,有時從網絡緩慢加載有關。如圖像

的文件可DOMContentLoaded事件觸發後document的,但嵌入的資源被加載。

所以,你可能只需要windowload事件,而不是:

window.addEventListener('load', function() { 
    // This code runs after all resources including images are loaded. 
}, false); 
+0

你的意思是'window.addEventListener('DOMContentLoaded',()=> {...});'而不是'document'開始?可悲的是,它沒有奏效。或者,也許我不明白是正確的。 – Arcticooling

+0

@Arcticooling'window.addEventListener('load',...)' –

+0

哦,對不起,好的,我應該閱讀'DOMContentLoaded'和'load'事件之間的區別。 – Arcticooling

相關問題