且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Ajax加载的页面片段中运行脚本

更新时间:2023-12-05 09:53:10

我通过制作一个新的简单的就绪处理程序系统来解决它,如下所示...

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;
})();

因此,在加载.ajax()的页面中,脚本被排队运行.

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
});

,并在进行插入的代码中,在update_ui_after_load()调用之前运行

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

ajaxOnLoad.fireOnLoad();

更完整的解决方案可以解析页面,查找脚本标签并自动将它们排队.但是,由于我可以完全控制要插入的片段,因此我更容易切换到使用ajaxOnLoad.onLoad.

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.