Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(document).ready equivalent in asynchronously loaded content

I have a UI (let's call it page 1) which has a lot of HTML and JavaScript in it. When some of the elements on page 1 are clicked, a jQuery UI Dialog is opened and loaded with a partial page (let's call that page 2):

$("#myDialog").dialog({ modal: true /* Other options */ });
$('#myDialog').load('page2Link', { }, function () { });
$('#myDialog').dialog('open');

Page 2 then has a bunch of HTML and JavaScript as well. Simplified example:

<script src="Scripts/page2Stuff.js" type="text/javascript"></script>

<div id="page2Body">
    <!-- More elements -->
</div>

I have JS inside page2Stuff.js that needs to wait until page 2 is completely rendered. Is there something I can use within this partial page to see if the new HTML has been added to the DOM? I have tried the following:

$('#myDialog').load('page2Link', { }, page2ReadyFunction);

This can't find page2ReadyFunction. I assume because .load runs the JavaScript in page2Stuff.js and then discards it or something?

The way I'm able to get it to work now it to use setTimeout and continually check to see if $('#page2Body') returns anything but this doesn't seem ideal.

like image 331
xbrady Avatar asked Oct 09 '22 01:10

xbrady


2 Answers

Instead of having your script tag at the beginning of your second page, put it at the end of it, after all the HTML, like this:

<div id="page2Body">
    <!-- More elements -->
</div>

<script src="Scripts/page2Stuff.js" type="text/javascript"></script>

Since the code will be executed according to source order, you can rest assured that the HTML will be ready by the time your script runs.

like image 171
Joseph Silber Avatar answered Oct 13 '22 11:10

Joseph Silber


When you run the load function, it is expecting page2ReadyFunction to exist at that exact time. It does not because you haven't loaded the script. The following would get around that problem but also shouldn't work because the script will load asynchronously:

$('#myDialog').load('page2Link', { }, function() {page2ReadyFunction();});

To get around that problem, you could do something like this:

$('#myDialog').load('page2Link', { }, function() {
    function tryPageLoad() {
        if(page2ReadyFunction)
            page2ReadyFunction();
        else
            setTimeout(tryPageLoad, 100);
    }
    tryPageLoad();
});

This function tries every 100ms to see if page2ReadyFunction exists and calls it when it does.

Of course, you shouldn't have to worry about any of this because the child script tag will load asynchronously and the rendering should happen before the JavaScript executes. You could verify this by using console.log to see what fires first, the JavaScript in the client script or the callback function.

like image 41
Brian Nickel Avatar answered Oct 13 '22 10:10

Brian Nickel