Can I call $(document).ready() to re-activate all on load event handlers?

Mike Richards picture Mike Richards · Aug 21, 2011 · Viewed 82.2k times · Source

Does anyone happen to know IF and HOW I could re-call all on-load event handlers? I'm referencing some .js files that I DON'T have control over, and these .js libraries do their initialization in $(document).ready(), and unfortunately don't provide any easy function to re-initialize.

I'm currently trying to replace a large div block with content from an ajax call, and so I have to re-initialize the external libraries. So, it would be nice just to call $(document).ready() in order to re-initialize EVERYTHING.

So far, I've tried this on the ajax call:

success: function(data) {
    alert('1'); // Displays '1'
    $('#content').html(data);
    alert('2'); // Displays '2'
    $(document).ready();
    alert('3'); // Does not display
}

Calling $(document).ready(); fails quietly too. JavaScript console shows no errors. Does anyone know if this is possible (without modifying javascript library files)?

Answer

jfriend00 picture jfriend00 · Aug 21, 2011

Since you asked how to do it without modifying the external JS files, I'll answer that way. I've traced through the .ready() function in jQuery in the debugger and it appears that the root function that gets called when the page is ready is this:

jQuery.ready();

But, it appears you cannot just call it again to accomplish what you want because it appears that when it fires the first time, it unbinds from the functions that were previously registered (e.g. forgetting them). As such, calling jQuery.ready() manually a second time does not retrigger the same function calls again and I verified that in the debugger (breakpoint was only hit once, not second time).

So, it appears that you cannot solve this problem without either changing the jQuery implementation so it doesn't unbind (to allow multiple firings) or changing each piece of ready handler code to use your own events that you can fire as many times as you want.