Javascript OnLoad Events


Getting javascript to play nice with other javascript can be a nightmare.

When scripts have been written with a callback function using window.onload or an onload in the body tag, it can more often than not, break other scripts that are using it too.

Below is the answer:

function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != ‘function’) {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}

addLoadEvent(nameOfTheFunctionToRunOnPageLoad);
addLoadEvent(function() {
/* more code to run on page load */
});


Leave a comment