1

I am loading a part of html through ajax. This part has javascript code that runs on document.ready. My understanding was that dom ready dependent code would not be executed because event has already been fired before ajax call happened.

However, that's not the case. I can see console.log placed inside document.ready.

Please explain whats happening.

Thanks in advance.

Charanjeet Kaur
  • 1,199
  • 3
  • 14
  • 27

1 Answers1

1

When some code uses $(document).ready(fn) after the document is already ready, then the callback is called immediately rather than waiting. That is jQuery's specific implementation of .ready(). It can tell if the DOM is already ready or if it has already fired other handlers.

In either case, it will just call the callback immediately (technically, it calls the callback with a short setTimeout()) so that it fires asynchronously.

Demonstration: http://jsfiddle.net/jfriend00/GYc6k/

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • How does it go with onreadystatechange? Tried Example http://jsfiddle.net/charanjeet2008/y5CGf/ – Charanjeet Kaur May 05 '14 at 05:03
  • @CharanjeetKaur - it depends upon your code when using onreadystatechange. See [here for code that uses onreadystatechange as one of it's methods](http://stackoverflow.com/questions/9899372/pure-javascript-equivalent-to-jquerys-ready-how-to-call-a-function-when-the/9899701#9899701) that is safe. – jfriend00 May 05 '14 at 05:05
  • @CharanjeetKaur - any code hooking up any form of document ready listener should first check to see if the document is already ready `if (document.readyState === "complete")`. If the document is already ready, then it should just execute the handler immediately. That's how jQuery.ready() does it and the [`docReady()`](http://stackoverflow.com/questions/9899372/pure-javascript-equivalent-to-jquerys-ready-how-to-call-a-function-when-the/9899701#9899701) plain JS implementation I linked to earlier. – jfriend00 May 05 '14 at 05:15