0

I've been using jQuery's $.ready() function for initialisation when loading webpages, but some of the pages dynamically load content later via $.ajax() calls long after the $.ready() call has completed.

The problem is I need an equivalent ready() function to initialise the dynamic content - I can't use $('.sel').ready() because ready() only applies to the document as a whole and attempting to initialise the content from $ajax.success() randomly fails because it appears some DOM elements in the dynamic content have not always loaded.

$.ready(function() {
     // init document here, then much later...
    $.ajax({
       url:/getdynamicstuff,
       success:function(dyndata) {
           // container is part of the main body, so this always works
           $('.container').html(dyndata);

           // try and use ready again once the container DOM is loaded...
           $().ready(function() {
                // this commonly (but not always) fails because $('.dynelement').length is 0 (i.e the element is not yet in the DOM)
                $('.dynelement').click();
           });
       }
    });
});

How do I trigger a callback once all the dynamic DOM elements have fully loaded?

adelphus
  • 10,116
  • 5
  • 36
  • 46
  • Have you tried using [ajaxcomplete](http://api.jquery.com/ajaxcomplete/)? – Arcanyx Jun 09 '15 at 11:14
  • This question might have the answer for you. You should be able to react to the creation of a named element : http://stackoverflow.com/questions/5525071/how-to-wait-until-an-element-exists – Steen Jun 09 '15 at 11:14
  • @Arcanyx my understanding is that the ajax request (and all associated functions, including ajaxcomplete) is *entirely separate* from when the DOM is loaded. It looks like the only way is to setup a MutationObserver as Steen suggests, but that seems like overkill. – adelphus Jun 09 '15 at 11:40
  • @adelphus Kindly read this answer - [stackoverflow link](http://stackoverflow.com/a/5240889/4404344) bcoz even though I haven't completely understood your point, I feel that this is what you are looking for. Happy coding!! – Arcanyx Jun 09 '15 at 12:24

0 Answers0