Run JavaScript on page load without adding code inside body tag

Run JavaScript on page load without adding code inside body tag, is as bellow:

if (window.addEventListener) { 
    // Chrome, Mozilla, Netscape, Firefox
    window.addEventListener('load', WindowLoad, false);
} 
else if (window.attachEvent) { 
    // IE
    window.attachEvent('onload', WindowLoad);
}

function WindowLoad(event) {
    alert("Yeppy... here is window onload Message.");
}

 

Note: Internet Explorer versions before IE 9 used the attachEvent() method should be there.

you may call/ assign directly function to onload event as bellow also:

window.onload=function(){SomeJavaScriptCode};

Leave a Reply