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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With