直接指派 window.onload = fn 會覆蓋先前綁定的函式。需使用相容函式追加多個載入事件。
function addLoadEvent(func) {
var oldOnload = window.onload;
if (typeof window.onload !== 'function') {
window.onload = func;
} else {
window.onload = function() {
oldOnload();
func();
};
}
}
// 使用方式
addLoadEvent(tt1);
addLoadEvent(tt2);
addLoadEvent(tt3);
function tt1() { alert('tt1'); }
function tt2() { alert('tt2'); }
function tt3() { alert('tt3'); }
tt1),而非呼叫(tt1()),原文範例有誤。window.addEventListener('load', fn) 或 document.addEventListener('DOMContentLoaded', fn),支援多重綁定且不互相覆蓋。window.addEventListener('load', tt1);
window.addEventListener('load', tt2);
window.addEventListener('load', tt3);