Sunny
Sunny

Reputation: 10075

Is " $(document).ready(function () " required for AJAX generated JS?

Please answer this question as I have failed to get proper understanding of the issue and simply cannot locate any material to read on it. The question, generically speaking, requires the consideration of the following commonly used structure. Yes, the JS may go at the bottom but that's a different discussion.

    <html>
     ...
    <script>
        $(document).ready(function () {
          ....  //Script to be used in this document
        });
    </script>
       ...more html
    <div id="ajax_div" ... > 
      <script>
         **$(document).ready(function ()** { //2nd wrapper
            ....
          });
      </script>
         ... AJAX returned HTML
    </div>

The question: Is the second wrapper required to be generated in the AJAX response? I understand that document.ready makes sure that the DOM is ready before the JS can work on it. Should the same logic, then, not apply to AJAX generated JS? Are there cases when it is required and when it is not required? I had a situation where the wrapper on-document-ready for AJAX generated JS fixed something but all along I have not been using it for other situations and all was well!!!

Hope its not a dumb question! If it is a repeat, please refer me to it. I could not locate any...

Upvotes: 3

Views: 1179

Answers (1)

Chandranshu
Chandranshu

Reputation: 3669

Consider the following scenario:

  1. You loaded a page in browser. The browser had to load some included javascript which was parsed as it was loaded.
  2. While the page was still loading:
    1. the parsed JS sent an AJAX request.
    2. the server sent back a response text
    3. The success() handler of the AJAX call wants to add the returned text into a div which is not yet loaded.
    4. error
  3. Document ready event triggers as document finishes loading.

Now, in step 2.3, it may happen that the returned code or the success/failure callbacks were capable of working with the partially loaded document since their targets were already loaded at that point of time. You'll then not notice any errors.

On the other hand, if the AJAX call itself is fired after the document is ready, then your generated JS doesn't have to wrap itself in a document.ready block.

Upvotes: 1

Related Questions