admin管理员组

文章数量:1355731

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>

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>
Share Improve this question edited May 10, 2014 at 23:41 Felix Kling 817k181 gold badges1.1k silver badges1.2k bronze badges asked May 10, 2014 at 23:36 Waterfr VillaWaterfr Villa 1,3171 gold badge13 silver badges36 bronze badges 7
  • 1 This also happens with console.log, instead of the blocking alert: jsfiddle/9fSgE. – Felix Kling Commented May 10, 2014 at 23:43
  • 2 @HalimQarroum what's the difference? It's just the way you write it, and makes more sense to execute the function () inside it's context ()); and as in any language we have agreed to use the correct punctuation makes sense to do the same in JS. Same for the lost curl, it would be better to use it in the same line where the function is stated. – Roko C. Buljan Commented May 10, 2014 at 23:45
  • @FelixKling yes, I thought also that was something to do with the blocking of alert(), seems not to be the case. Neither makes difference placing the calls in head or before </body> – Roko C. Buljan Commented May 10, 2014 at 23:49
  • Playing around a bit: If you add direct console.log calls between the IIFE's, you can see that loaded is directly called after the first IIFE terminates: jsfiddle/9fSgE/1. However, if you unwrap the first IIFE, then the loaded call appears at the very end, not after the second IIFE: jsfiddle/9fSgE/2. Unfortunately this doesn't bring me any closer to an explanation :-/ – Felix Kling Commented May 10, 2014 at 23:51
  • 3 +1 Fascinating question. Can't wait for a decent explanation. Would be better updated to the console.log version as this, to me, is truly mystifying, whereas with alert it seems to make more sense. – spender Commented May 10, 2014 at 23:52
 |  Show 2 more ments

1 Answer 1

Reset to default 18

You forgot ; after window onload function expression. So it bees:

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.

本文标签: Javascript strange loading sequenceStack Overflow