可能重複:
$(document).ready equivalent without jQuery如何知道什麼時候頁面準備就緒而不使用jQuery(替代方法)?
如果你的jQuery中調用的頁面。你可以簡單地做到這一點:
$(document).ready(function() { /** code inside **/});
但如何做到沒有jQuery類似的事情?
可能重複:
$(document).ready equivalent without jQuery如何知道什麼時候頁面準備就緒而不使用jQuery(替代方法)?
如果你的jQuery中調用的頁面。你可以簡單地做到這一點:
$(document).ready(function() { /** code inside **/});
但如何做到沒有jQuery類似的事情?
您可以使用DOMContentLoaded
事件。
document.addEventListener('DOMContentLoaded', function() {
// ...
});
注意,在舊的IE中,你需要的解決方法,一些使用readystatechange
事件,如果我沒有記錯。
使用下面的腳本:
<script type="text/JavaScript">
function funtionToBeCalled(){
// code that will be exected after dom ready
}
window.onload=funtionToBeCalled;
</script>
或者還有一個辦法。身體標記添加onload事件如下:
<body onload='functionToBeCalled();'>
</body>
我想回答你的問題的最簡單的方法是回答「如何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();
}
}
你應該注意到,'準備好()'是一旦DOM準備調用,這可能是前一段時間'onload'事件觸發。 (正如你可能在jQuery源代碼中看到的那樣,這並不總是發生,因爲'onload'是後備)。 – scraimer 2011-12-20 13:16:21