My web app dynamically loads sections of its UI with jquery.ajax. The new UI sections come with script though. I’m loading them as such:
Use…
$.ajax({
url: url,
dataType: 'html',
success: function(data, textStatus, XMLHttpRequest) {
$(target_selector).html( data );
update_ui_after_load();
}
});
This almost works. The problem is that the scripts included in the dynamic part of the page run before the new page fragment is inserted into the DOM. But often these scripts want to modify the HTML they’re being delivered with. My best hacky solution so far is just to delay the scripts some reasonable amount of time to let the DOM insertion happen, by wrapping them in a setTimeout:
window.setTimeout( function() {
// process downloaded Fragment
}, 300);
Obviously this is unreliable and hideous. What’s a better way?
I solved it by making a new simple ready handler system as follows…
So in the pages which get
.ajax()loaded, the scripts are queued to run withand in the code which does the insertion, before the
update_ui_after_load()call, runA more complete solution could parse the pages, find script tags, and queue them up automatically. But since I have complete control of the fragments being inserted, it’s easier for me to switch to using
ajaxOnLoad.onLoad.