I've tried to understand that reading other topics about it here on SO, but I couldn't find clear answer.
I've also checked https://api.jquery.com/ready/ and https://api.jquery.com/load-event/
Of course, it doesn't always happen.
Load before ready (no content)
Load after ready (with image) - but only for the first time you visit that pen, when you refresh it (or you have excellent internet connection and you download 1MB in 1ms ;)) - load event will fire before ready because you already have that image in browser cache.
I know how to partially "fix" this, but I'm more interested in why it happens.
var windowLoaded = false;
$(function() {
console.log('Ready'); // Good - it will always fire **before** load event
});
$(window).on('load', function() {
windowLoaded = true;
});
$(function() {
if(windowLoaded) { // (1)
console.log('Loaded');
} else {
$(window).on('load', function() {
console.log('Loaded');
});
}
});
$(function() {
console.log('Ready'); // Bad - it will sometimes fire **after** load event - when `windowLoaded` is true in if statement (1)
});
But this "fix" isn't bulletproof - see code comments