Charanjeet Kaur
Charanjeet Kaur

Reputation: 1197

Document Ready event on ajax loaded javascript

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.

Upvotes: 1

Views: 361

Answers (1)

jfriend00
jfriend00

Reputation: 707318

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/

Upvotes: 1

Related Questions