2

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.

Possible fix:

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

max
  • 8,632
  • 3
  • 21
  • 55
  • @vol7ron First of all there is no `DOMContentReady` in JavaScript, secondly this is another issue with jQuery, when you use default Javascript `DOMContentLoaded` and `onload` events without jQuery, `onload` will **always** be fired after `DOMContentLoaded`. Browser doesn't really matter (I'm using Chrome 59 on Mac). – max Jul 06 '17 at 02:41
  • I understand your point, but there is no answer for that reagarding to jQuery. Searching google isn't enough. I found only this from jQuery's GitHub: "To be clear, we understand what's causing this. We recently made ready handlers fire asynchronously. This has advantages that are hard to give up. The disadvantage is that the ready handler can sometimes fire after the load event if the load event fires quickly enough." – max Jul 06 '17 at 03:19
  • @vol7ron I just would like to know how it works. I don't have any use cases. I think it's enough for SO question (to learn something new). – max Jul 06 '17 at 03:58
  • Ok, but why in jQuery 1.x and 2.x load event always (maybe not as you mentioned) fire after ready? I know that load waites for images, stylesheets etc. but doesn't it wait also for DOM? I think it does, because as you can see there is very small difference in my first Codepen example (like 10ms between load and ready). – max Jul 06 '17 at 04:16
  • No issue here: https://codepen.io/makshh/pen/NgBdZe?editors=0110 – max Jul 06 '17 at 04:24

0 Answers0