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.
I assume the scripts are doing manipulation upon the DOM elements you're adding through AJAX.
jQuery has an
isReady
property that it sets once theready
event has been triggered on the page.Any subsequent calls to
jQuery.ready(...)
will first check thisisReady
flag. If the flag is set to true, it will call the handler immediately. You can see why this would cause problems in your code.One option would be to load the response into a jQuery fragment and parse out all of the
<script />
tags for execution later.@Dan has the answer. When loading scripts via ajax the document
isReady
is true. This means if this is the script tag that is requested by your ajax request:Instead of parsing utilize JSON. One property will hold HTML. Another property will hold the scripts.
Then you can do this:
Also if you load scripts with the ready function surrounding you code it will create a closure. this closure will last the lifetime of the page. Memory leaks will be created every time you request that script without refreshing your page