Skip to content Skip to sidebar Skip to footer

Running Scripts In An Ajax-loaded Page Fragment

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: '

Solution 1:

Using

$(function);

will make the function you pass to jQuery to be run after the fragment is inline on the page. I found it in ASP.NET Ajax partial postback and jQuery problem after looking at your question.

Solution 2:

Are you familiar with the live() function? Might be what you're looking for here.

http://api.jquery.com/live/

Solution 3:

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.

I'm fairly sure that in that case, the only sensible thing is to place the script after the HTML element.

Everything else would become kludgy quickly - I guess you could implement your own "ready" handler that gets executed after your HTML has been inserted, but that would be a lot of work to implement for no real gain.

Solution 4:

I solved it by making a new simple ready handler system as follows...

var ajaxOnLoad = (function() {
    var ajaxOnLoad = {};
    var onLoadQueue=[];

    ajaxOnLoad.onLoad= function(fn) {
        onLoadQueue.push(fn);
    }           

    ajaxOnLoad.fireOnLoad = function() {
        while( onLoadQueue.length > 0 ) {
            varfn = onLoadQueue.shift();
            fn();
        } 
    } 

    window.ajaxOnLoad = ajaxOnLoad;
    return ajaxOnLoad;
})();

So in the pages which get .ajax() loaded, the scripts are queued to run with

ajaxOnLoad.onLoad( function() {
    // Stuff to do after the page fragment is inserted in the main DOM
});

and in the code which does the insertion, before the update_ui_after_load() call, run

ajaxOnLoad.fireOnLoad();

A 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.

Post a Comment for "Running Scripts In An Ajax-loaded Page Fragment"