Search code examples
javascripthtmldom-eventsonload

Alternate to body onload = (string) for Javascript


I'm (somewhat) new to JavaScript and I'm writing a timing plugin that requires

<body onload="mktClock_standard(); setInterval('mktClock_standard()', 1000 ); mktClock_military(); setInterval('mktClock_standard()', 1000 )">

And I was wondering if there's a way to do that, but in JavaScript, like using window.onload or something. I tried simply:

window.onload = mktClock_standard(); setInterval('mktClock_standard()', 1000 ); mktClock_military(); setInterval('mktClock_standard()', 1000 )

But obviously there are so many wrong syntax errors and stuff, so... I went to Google but I could not find anything relating to my problem. Any ideas?


Solution

  • window.onload is the exact same thing as the onload attribute, but it expects a function:

    window.onload = function() {
        mktClock_standard(); 
        setInterval('mktClock_standard()', 1000 ); 
        mktClock_military(); 
        setInterval('mktClock_standard()', 1000 )
    }
    

    Actually, when you add code to attributes like <body onload="code...">, the browser will treat them as if there were a wrapping anonymous function.

    Also, modern browsers support the DOMContentLoaded event, which is similar, but fires ealier. It fires as soon as the DOM is loaded, while window.onload waits for other resources (such as images) to be loaded. To bind to DOMContentLoaded, use addEventListener:

    document.addEventListener('DOMContentLoaded', function(evt) {
        // event handler code here
    });
    

    (The above won't work in IE8 and earlier)