why $(document).ready() run after window.onload?

Viewed 154

in this thread its answered the window.onload is the most late when compared to jquery.ready

https://stackoverflow.com/a/3698214/15185328

Also in this thread its stated the vanilla JS version of jquery ready is DOMContentLoaded (which is run much earlier than window.onload):

$(document).ready equivalent without jQuery

But when I tested it. jquery.ready is the most late compared with other event. Why is it?

jQuery(document).ready(function() {
  console.log("ready (jquery)");
});

jQuery(window).on("load", function() {
  console.log("onload (jquery)");
});

window.addEventListener("load", function(e) {
  console.log("onload (js)");
});

window.addEventListener('DOMContentLoaded', function() {
  console.log("DOMContentLoaded (js)");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>

Jsfiddle: https://jsfiddle.net/jvdw0kh8/

1 Answers

jQuery internally has a variable named readyList, which is a Deferred object that resolves when DOMContentLoaded fires. All calls to .ready go through that.

Once DOMContentLoaded fires, the deferred resolves, and all handlers connected to it fire. But, like Promises, handlers connected to the Deferred don't fire immediately - it takes place a bit of time later (after the equivalent of an immediate setTimeout).

jQuery( document ).ready(function() {
  console.log("ready (jquery)");
});  


window.addEventListener('DOMContentLoaded', function(){
    console.log("DOMContentLoaded (js)");
    setTimeout(() => {
      console.log('DOMContentLoaded microtask');
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>

Related