Hook a javascript event to page load

Jagd picture Jagd · Jun 3, 2009 · Viewed 57.6k times · Source

I have an aspx that has the following javascript function being ran during the onload event of the body.

<body onload="startClock();">

However, I'm setting the aspx up to use a master page, so the body tag doesn't exist in the aspx anymore. How do I go about registering the startClock function to run when the page is hit and still have it use a masterpage?

Answer

Corbin March picture Corbin March · Jun 3, 2009

If you don't want to explicitly assign window.onload or use a framework, consider:

<script type="text/javascript">
function startClock(){
    //do onload work
}
if(window.addEventListener) {
    window.addEventListener('load',startClock,false); //W3C
} else {
    window.attachEvent('onload',startClock); //IE
}
</script>

http://www.quirksmode.org/js/events_advanced.html