arvgta arvgta - 6 months ago 53
Javascript Question

Refire ready event after AJAX reload

I've researched other threads and am just confused.

Situation: I'm supplying a generic jQuery plugin that loads the div the user specifies dynamically via AJAX. Everything works fine, but on e.g. one user's page, there is a piece of JS that is not called, because the "ready" event is not refired.

The usual situation will be that the user's other jQuery stuff will be placed after jQuery(document).ready.

I've just tested calling:

$(document).trigger('ready');


manually - it has no effects at all, as I presume that "ready" is called only once and only once.

What is the proper way to handle it?
(it would be great to provide the most generic solution possible)

I'd love to do something like suggested in this thread:

jquery : trigger $document.ready (so AJAX code I can't modify is executed)

But I think that readyList is now private and can't be manipulated directly anymore?

It's worth mentioning, that the plugin I'm providing supplies a callback functionality for the user. Of course, (s)he could place post-loading handling JS code in there.

Thanks in advance and kind regards

Answer

You shouldnt attempt to reload the entire DOM ready function. Particularly harmful is the n+n nature of events if you did, 2 click events on the same element for example could potentially become 4, then 8 etc. if the DOM ready function is repeatedly re-fired by them.

You can avoid this by taking out the code that you need to run once you're done with your ajax call and presumably the population of the element that you're hoping would benefit from the event you wish to re-initialise.

$(document).ready(function()
{
    initialise();

    //... Resume with DOM ready
}

function initialise()
{
    // create event here that needs re-initialising
}

So when you're done with your ajax call just call initialise() again.

Alternatively look to using .on and using it's bubbling up capabilities, this is how I would handle this kind of problem. It avoids you having to ever think about 're-initialising' any part of the DOM ready functions in your scripts.

Additional from comments

.on allows you to bind events to low level elements on the page that do not change at any time, whilst allowing you to control which of the dynamic elements actually trigger the event within that container.

<div id="container">

    <div id="ajax-content">

        <a href="#" class="created-link">A new link</a>

    </div>

</div>

So we know that the <a> is created by an ajax function after the DOM ready event is fired, therefore any direct events applied to it then would not work.

Instead we would bind the event to a lower level unchanged element and bubble up to the containing dynamic DOM element.

$('#container').on('click', '.created-link', function(event)
{
    event.preventDefault();

    // Your normal on click code
}