Shailin
Shailin

Reputation: 11

Dynamic Script with document.ready() listener not executing with ajax call

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 ..

Upvotes: 1

Views: 137

Answers (2)

Ian
Ian

Reputation: 50933

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.

Upvotes: 1

Niels
Niels

Reputation: 49929

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

Upvotes: 1

Related Questions