0

When calling content via ajax (using jQuery) - if there are ajax interactions in the ajax-loaded content, should jQuery be called again in that file? if there are scripts/plugins that are to be called only in the ajax-loaded content, should they be called only in the ajax-loaded content, or in the parent file?

Thanks!

kneidels
  • 956
  • 6
  • 29
  • 55

1 Answers1

1

The short answer to your question is that I would suggest handling anything related to the ajax-loaded content in the original ajax call (or as you called it, the "parent" file). Given that you did not post any code, I cannot use any examples specific to your scenario, however something like is what you want to do:

$.ajax({
  url: "/foo",
  success: function(response) {
    do_something_related_to_this_content(response);
  }
});

do_something_related_to_this_content = function(response){
    // This function contains the code you originally 
    // wanted to put in the ajax-loaded content.
}

If you were to put your javascript within the ajax-loaded content, one problem I would worry about is that your ajax-loaded script might have dependencies that are assumed to exist in the "parent" file, however should that change (IE you load your ajax-content in a completely different context), suddenly your code breaks.

In addition, your ajax-loaded code would get loaded multiple times if you reload that same content more than once.

Finally, as memory serves, if your code were within a <script> block, I do not believe it would automatically get called when loaded through AJAX (attempting to find this out concretely...stand by)

Hope that makes sense.

EDIT:

Regarding <script> blocks loading, check out this answer, which confirms what I wrote. You would have to perform an eval() on the <script> block content.

Community
  • 1
  • 1
Paul Richter
  • 10,908
  • 10
  • 52
  • 85