My site was using jquery.load()
to do navigation on a big chunk of the page. I really appreciate the ability to only include only a particular part of the loaded content, here the div with id="content":
$(frame_selector).load(url +" #content", function(response, status, xhr) {...});
But now I need to be able to run scripts that are part of the pages being loaded dynamically. Jquery.load()
strips out these scripts, but jquery.ajax()
doesn't. So I duplicated the partial-content functionality of jquery.load
in an ajax call as such:
$.ajax({
url: url,
dataType: 'html',
success: function(data, textStatus, XMLHttpRequest) {
// Only include the response within the #content id element.
$(frame_selector).html( jQuery("<div>")
.append(data)
.find("#content")
);
}
});
The problem is that the scripts which are being dynamically loaded from the ajax call aren't running reliably. Sometimes they don't seem to have any effect, perhaps because they're running too early. The scripts are just doing DOM manipulation in jquery -- not relying on images or flash or anything that's not supposed to be loaded yet. To keep from getting stuck I have this hideous hack to get things working. Instead of the AJAX-loaded script just using:
$(document).ready( function() {...} ); // unreliable
I delay the script 200ms before running:
$(document).ready( window.setTimeout( function() {...}, 200 )); // HATE THIS
Anybody know how I can make this work reliably without hard-coding a delay? I'm guessing it's a race condition between the <script>
and my logic to load #content
into a new div, but I'm not sure what to do about it.