简体   繁体   English

使用Ajax加载页面并在必要时加载新脚本

[英]Load page with Ajax and load new scripts if necessary

I have a page1 which has a wrapper with articles. 我有一个page1,其中有一篇文章包装纸。

<div id="wrapper">
    <article>...</article>
    <article>...</article>
    <article>...</article>
    <article>...</article>
</div>

I am loading new articles from page2 with Ajax and appending them to the wrapper 我正在使用Ajax从page2加载新文章并将其附加到包装器中

    $.ajax({
        url : page_to_load,
        success : function (data) {

            $('article',data).appendTo('#wrapper');

        }
    });

But some of this new articles might need specific scripts that were not loaded in page1 but would be loaded if accessed directly page2. 但是,其中一些新文章可能需要特定的脚本,这些脚本未在page1中加载,但是如果直接访问page2将被加载。

So the problem is some of the content in new articles breaks as they are missing those scripts. 因此,问题在于新文章中的某些内容中断,因为它们缺少这些脚本。

What is the best solution? 最好的解决方案是什么? I can think of checking the new loaded page scripts and compare them with the already loaded and download the new ones, but I have no idea of how to do this. 我可以考虑检查新加载的页面脚本,并将其与已加载的页面脚本进行比较并下载新的脚本,但是我不知道如何执行此操作。


EDIT 编辑

I noticed if I set the dataType to 'html' I cant search for the scripts, although they are there: 我注意到如果将dataType设置为“ html”,尽管它们存在,但我无法搜索脚本:

$('script',data)//doesn't match anything

But if I do: 但是如果我这样做:

console.log(data);

I can see the whole page with <html> and <script> tags 我可以看到带有<html><script>标记的整个页面

There is no problem actually, if you append HTML to the Dom then script calls will be interpreted as if the page was loaded directly, just make sure you use the same parameters as the shorthand jquery $.POST method. 实际上没有问题,如果将HTML追加到Dom上,则脚本调用将被解释为直接加载页面,只需确保使用与速记jquery $ .POST方法相同的参数即可。

I actually do this all the time and the <script src=""> are called and interpreted correctly 我实际上一直在这样做,并且<script src="">被正确地调用和解释

Just make sure you're accessing the scripts from the right scope as if the html was hardcoded on page1. 只要确保您从正确的范围访问脚本,就好象html是在page1上硬编码的。

If this doesn't work, then check with the web inspector if the scripts are loaded or not. 如果这不起作用,请与Web检查器检查脚本是否已加载。

不确定,但是也许您可以在AJAX调用中添加脚本-我不确定,因为我没有尝试过:

Proxy.Scripts.Add(new ScriptReference(AddVersion("/Pages/Items/SearchList/SearchList.Grid.js" )));

Working solution: 工作解决方案:

$.ajax({
    url : page_to_load,
    success : function (data) {
        // load the scripts
        var dom = $(data);
        dom.filter('script').each(function(){
            var scriptSrc = $(this).attr('src');
            if(!$('script[src="'+ scriptSrc +'"]').length && scriptSrc !== undefined) {
                var script = $("<script/>");
                script.attr('src', scriptSrc);
                $("head").append(script);
            }
        });
        // load the articles
        $('article',data).appendTo('#wrapper');
    }
});

This workflow should work : 此工作流程应工作:

  1. After every page request : 在每个页面请求之后:
  2. Get all the script tags in the loaded page. 在加载的页面中获取所有脚本标签。
  3. Loop over the scripts 遍历脚本
  4. If it's not loaded yet , load it. 如果尚未加载,请加载它。

Here is the code snippet : 这是代码片段:

$.ajax({
    url : 'http://localhost',
    success : function (data) {
        $('article',data).appendTo('#wrapper');
        $.each($.parseHTML(data,null,true),function(){
          if($(this)[0].tagName == "SCRIPT"){
              var src = $(this).attr('src');
                if($('script[src="'+ src +'"]').length){
                    $.getScript(src);
            }
        });
    }
});

Disable async. 禁用异步。

$.ajax({
  url : page_to_load,
  async: false, 
  success : function (data) {  
   $('article',data).appendTo('#wrapper');
  }
});

you can use RequireJS or HeadJs library for calling js files. 您可以使用RequireJS或HeadJs库来调用js文件。

RequireJS is a JavaScript file and module loader and HeadJS, a small library for Responsive Design, Feature Detections & Resource Loading RequireJS是一个JavaScript文件和模块加载器,还有HeadJS,这是一个用于响应式设计,功能检测和资源加载的小型库

HeadJs is great and useful, try it. HeadJs非常有用,请尝试一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM