How can I achieve $ (document) .ready type behavior for AJAX content?

$(document).ready(handler) is executed after the DOM is fully loaded. If the content is later added to the page using AJAX, which contains the $(document).ready(handler) function, this function is executed immediately, in the jQuery API . In addition, .ready can only be called on a jQuery object corresponding to the current document.

However, this is not what I want :)

How can I achieve this type of .ready functions for data loaded via AJAX after .ready already running using a cross browser?

EDIT: Here's a very simplified example. I have a problem that I'm trying to solve, but I'm more interested in how to do it right.

Basically, the .ready function in ajaxPage.html is run before importantDependency.js is fully loaded, so the first load of ajaxPage, importantDependency is missing, but subsequent loads see it.

index.html

 ... <script type="text/javascript"> $(document).ready(function() { alert("The document is ready"); $('#myButton').click(function() { $('<div></div>').dialog({ open: function () { $(this).load('ajaxPage.html'); } }); }); }); </script> ... 

ajaxPage.html

 ... <script type="text/javascript" src="importantDependency.js"></script> <script type="text/javascript"> $(document).ready() { $('#thing').leverageImportantDependency(); }); </script> ... 

EDIT 2: I want to do this from the loaded content, and not from the page that calls the content. Changing the calling page means duplicating the code in each instance where it is called. I would like the behavior to be tied to the content, and not to its name.

+4
source share
3 answers

Typically, you need to do something like this:

 $("#container").load(function(html) { // container has been filled up, and is // ready for JS processing doSomethingWithNewContent(); }); 

That is, work something after the contents have been replaced using the appropriate ajax callback. Other examples:

 $.get("foo.html", function(html) { $("#container").html(html); $("#container").find(".foo").fancyThing(); }); $.ajax({ url: 'foo.html', type: 'post', success: function(html) { $("#container").html(html).find(".foo").hide(); } }); 

Cm:

EDIT: from what I understand from your editing, you want to attach something, like an event handler or a plugin, to some elements that continue to be replaced. There are several ways to do this:

+3
source

I'm not sure I had a question, but when you get the data, you just do whatever you want with the ajax call success handler:

  $.ajax({ url: pageUrl, success: function (data) { $(".someContainer").html(data); // TODO: This is your ready handler for the new content } }); 
+1
source

You can use the full jQuery Ajax call property. The full function is called after success or error.

 $.ajax({ url: "foo", complete: function({ // I'm done } }); 

See: http://api.jquery.com/jQuery.ajax/

0
source

Source: https://habr.com/ru/post/1332245/


All Articles