2011-12-20 64 views
26

可能重複:
$(document).ready equivalent without jQuery如何知道什麼時候頁面準備就緒而不使用jQuery(替代方法)?

如果你的jQuery中調用的頁面。你可以簡單地做到這一點:

$(document).ready(function() { /** code inside **/}); 

但如何做到沒有jQuery類似的事情?

+0

你應該注意到,'準備好()'是一旦DOM準備調用,這可能是前一段時間'onload'事件觸發。 (正如你可能在jQuery源代碼中看到的那樣,這並不總是發生,因爲'onload'是後備)。 – scraimer 2011-12-20 13:16:21

回答

30

您可以使用DOMContentLoaded事件。

document.addEventListener('DOMContentLoaded', function() { 
    // ... 
}); 

注意,在舊的IE中,你需要的解決方法,一些使用readystatechange事件,如果我沒有記錯。

+5

假設你不關心支持舊瀏覽器... – nnnnnn 2011-12-20 13:13:10

+0

謝謝,亞歷克斯,不錯的代碼! – Ito 2011-12-20 13:24:56

+0

請注意'DOMContentLoaded'在CSSOM加載之前觸發。因此,在沒有jQuery的情況下使用'DOMContentLoaded'的任何人都必須首先手動觸發頁面重排/重繪。 – user31782 2017-03-22 08:48:13

1
window.onload = function(){ 
// do something 
} 
+7

這與DOM準備就緒不一樣。 – alex 2011-12-20 13:20:45

+0

謝謝,現在工作! – Ito 2011-12-20 13:24:27

-2

使用下面的腳本:

<script type="text/JavaScript"> 
function funtionToBeCalled(){ 
// code that will be exected after dom ready 
} 

window.onload=funtionToBeCalled; 
</script> 

或者還有一個辦法。身體標記添加onload事件如下:

<body onload='functionToBeCalled();'> 
</body> 
13

我想回答你的問題的最簡單的方法是回答「如何jQuery的做呢?」爲此,我建議尋找作爲源代碼。代碼的最相關的部分是在 https://github.com/jquery/jquery/blob/master/src/core.js#L423

這裏有一個片段:

// Catch cases where $(document).ready() is called after the 
// browser event has already occurred. 
if (document.readyState === "complete") { 
    // Handle it asynchronously to allow scripts the opportunity to delay ready 
    return setTimeout(jQuery.ready, 1); 
} 

// Mozilla, Opera and webkit nightlies currently support this event 
if (document.addEventListener) { 
    // Use the handy event callback 
    document.addEventListener("DOMContentLoaded", DOMContentLoaded, false); 

    // A fallback to window.onload, that will always work 
    window.addEventListener("load", jQuery.ready, false); 

// If IE event model is used 
} else if (document.attachEvent) { 
    // ensure firing before onload, 
    // maybe late but safe also for iframes 
    document.attachEvent("onreadystatechange", DOMContentLoaded); 

    // A fallback to window.onload, that will always work 
    window.attachEvent("onload", jQuery.ready); 

    // If IE and not a frame 
    // continually check to see if the document is ready 
    var toplevel = false; 

    try { 
     toplevel = window.frameElement == null; 
    } catch(e) {} 

    if (document.documentElement.doScroll && toplevel) { 
     doScrollCheck(); 
    } 
} 
+0

+1,正準備發佈相同的內容。 – karim79 2011-12-20 13:17:08

+1

非常酷,內容豐富,讓我想看看jQuery的源代碼 – konkked 2015-02-16 12:42:48

相關問題