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!

2
  • question's not clear and hard to understand problem statement. Be more specific please. Commented Mar 19, 2013 at 17:40
  • i am intentionally being general because i am trying to understand the principle. Commented Mar 19, 2013 at 17:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.