Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript strange loading sequence

Tags:

javascript

In the code below I expected to see the following sequence

1, 2, loaded 

but I get

1, loaded, 2

Why?

<html>
<script>
window.onload = function()
{
    alert('loaded');
}

(function ()
{
    alert('1');
}());

(function ()
{
    alert('2');
}());

</script>
<body>
</body>
</html>
like image 957
Waterfr Villa Avatar asked May 10 '14 23:05

Waterfr Villa


1 Answers

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.

like image 129
dfsq Avatar answered Nov 04 '22 19:11

dfsq