Take the following code:
HTML
<button id="button>click me</button>
JS - VERSION 1
window.onload = init;
function init() {
console.log('init called');
var button = document.getElementById('button');
button.onclick = buttonClickHandler;
}
function buttonClickHandler() {
console.log('button clicked');
}
vs Same HTML
JS - VERSION 2
window.onload = init();
In both cases, 'init called' appears in the console "immediately", but in the second case, it is followed by an error stating button is null.
There are 2 things at play here. 1) In version 1, it waits for the DOM to load 2) in version 2, it's happening before the DOM is loaded, or so it seems.
My question. Please explain as clearly as possible what is happening in version 1 vs what is happening in version 2. What are the technical terms for what window.onload = init
is vs what window.onload = init()
is? Also please explain each versions behaviour. Why does 1 wait, but 2 doesn't?
The script needs to go before the button element e.g. in the head: http://jsfiddle.net/XMEjr/1/