Running scripts in an ajax-loaded page fragment

前端 未结 4 1751
谎友^
谎友^ 2021-01-23 06:40

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



        
相关标签:
4条回答
  • 2021-01-23 07:12

    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.

    0 讨论(0)
  • 2021-01-23 07:22

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

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

    0 讨论(0)
  • 2021-01-23 07:25

    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.

    0 讨论(0)
  • 2021-01-23 07:35

    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 ) {
                var fn = 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.

    0 讨论(0)
提交回复
热议问题