In the code below I expected to see the following sequence
1, 2, loaded
but I get
1, loaded, 2
Why?
You forgot ;
after window onload
function expression. So it becomes:
window.onload = function () {
console.log('loaded');
}(function() { console.log('1'); }())
So onload
function is immediately executed with a one parameter, which is a result of another IEFE. Hence
function() { console.log('1'); }()
is executed first, and immediately after that window.onload
function expression. Then console.log('2')
expression.
Great example why it's important not to forget semicolons at the end of the lines.