Search

11/30/2007

Dean Edwards: The window.onload Problem - Solved!

Dean Edwards: The window.onload Problem - Solved! - 本來探討 window.onload,通常window.onload = init; init會等到頁面所有的compoent load完之後開始動作(包含所有的img & binary content),這樣有時候不是很理想,譬如一個很多圖的頁面,必須等到圖全部load完才會開始執行init,FF可以利用"DOMContentLoaded" IE可以利用defer來達成。
1. conditional comment

<!--[if IE]> ... <![endif]-->

conditional compilation
/*@cc_on @*/
/*@if (@_win32)
document.write("<script defer src=ie_onload.js><\/script>");
/*@end @*/

2. Mozilla Firefox
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}

Internet explorer
<script defer src="ie_onload.js" type="text/javascript"></script>

Dean Edwards: window.onload (again)

// for Internet Explorer (using conditional comments)
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*@end @*/


http://livepipe.net/scripts/code_highlighter.js

function asap(fn) {
asap.done ? setTimeout(fn, 0) : asap.waiting.push(fn);
}
asap.waiting = [];
asap.done = 0;
asap.ready = function() {
// (note: deliberately avoids using 'this')
if (!asap.done++) {
asap.timer && clearInterval(asap.timer);
var funcs = asap.waiting;
for (var i = 0, l = funcs.length; i < l; i++) {
setTimeout(funcs[i], 0);
}
}
}
// IE
/*@cc_on@if(@_win32)document.write('')@end@*/
// Moz/Op
document.addEventListener && document.addEventListener('DOMContentLoaded', asap.ready, false);
// Safari
asap.timer = navigator.userAgent.match(/WebKit|KHTML/i) && setInterval(function() { document.readyState.match(/loaded|complete/i) && asap.ready() }, 10);
// Fallback
window.onload = asap.ready;

之後要呼叫的function都經由 asap('Syntax.init()'); 這樣呼叫即可

沒有留言: