在Ajax加载的页面片段中运行脚本 [英] Running scripts in an ajax-loaded page fragment

查看:64
本文介绍了在Ajax加载的页面片段中运行脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Web应用使用jquery.ajax动态加载其UI部分.新的UI部分附带了脚本.我正在这样加载它们:

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:

使用...

$.ajax({
  url: url,
  dataType: 'html',
  success: function(data, textStatus, XMLHttpRequest) {
      $(target_selector).html( data );
      update_ui_after_load();
  }
});

这几乎可行.问题在于,页面的动态部分中包含的脚本会在新页面片段插入DOM之前运行.但是通常这些脚本想要修改与它们一起交付的HTML.到目前为止,我最好的hacky解决方案是将脚本包装在setTimeout中:

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

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.

这篇关于在Ajax加载的页面片段中运行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆