1

I used jQuery plugin with version 1.8.1 in my page . I created one function which creates dynamic script as per the below code and I place it inside the BODY of the HTML page.

<script> $(document).ready(function(){ // .... Some javascript }); </script>

The above dynamic script gets some additional HTML and JQuery using AJAX and appends it to the Body tag but it does not execute after Ajax completes. If I add a simple alert('something') like below then it does execute.

<script> alert('something'); $(document).ready(function(){ // .... Some javascript }); </script>

Please tell me what is issue i want execute dynamic script with document.ready() without alert() box ..

1
  • Ajax is asynchronous. $(document).ready() doesn't wait until the ajax is complete. alerts block all javascript execution, but not http requests, so the ajax then completes before the document ready event handler is triggered. The solution is to not code that way. Place all code that needs the ajax to be complete in the ajax's success handler. (also, don't use alerts to debug...) Commented Apr 22, 2013 at 17:23

2 Answers 2

1

This is because the document ready event already occured. Because your page has already been completely loaded. You have to solve this another way.

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

Comments

1

In order to know when the AJAX is done and the Document is ready, you could use something like this:

var docReady = new $.Deferred();
var ajaxDone = $.ajax({
    url: "whatever",
    type: "GET",
    blah blah blah
});

$(document).ready(function () {
    docReady.resolve();
});

$.when(ajaxDone, docReady).done(function () {
    // Document is ready and AJAX request is successful
});

If the AJAX request fails (for whatever reason), then the $.when().done callback doesn't execute. It requires that both deferred objects complete successfully. If you don't care if the AJAX is successful or not, change the .done to .then.

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.