John C John C - 1 year ago 173
Javascript Question

After a jQuery load command is there a way to force a wait until the html has been rendered into the div?

I have (basically) this code -

<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#loadDiv").load("mypage.html", function(){ alert($("#loadDiv #someText").text()) });
<div id="loadDiv"></div>

However the alert will display "undefined" since the html has not been rendered into the div yet.

I've seen this question - How to wait for jQuery's load function to render loaded content before executing callback function - and Jake's answer is the best for my situation. On my actual page I have eight of these and with a two second delay there are still some of them running before the html is rendered.

Does anyone have a better suggestion than increasing the delay to silly times?

Answer Source

According to the documentation, the load method already waits for the content to be placed in the element before calling the function:

"If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed."

I have tested this, and it does find the loaded content in the element when the callback function runs.

If it doesn't work in your code, you are trying to do something other than what you have shown in the question.