1

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/

Phil
  • 157,677
  • 23
  • 242
  • 245
gidiwe2427
  • 109
  • 1
  • 7

1 Answers1

2

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>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • So its wrong to say function inside jquery.ready run before window.onload? Can you recommend me on what event should i hook into to guarantee the most late without settimeout? native jquery/js event preferred – gidiwe2427 Jan 10 '22 at 05:15
  • @gidiwe2427 what's your use-case? If you need access to elements, then either jQuery's _ready_ or `DOMContentLoaded` should be fine. If you need to wait for other assets to load, what are they? – Phil Jan 10 '22 at 05:19
  • 1
    If you have multiple scripts with depend on a particular execution order, and all use `.ready`, the best approach by far would be to refactor them so that you only have a single entry point, with a single `.ready`, inside which you can order other function calls as desired. – CertainPerformance Jan 10 '22 at 05:43