卸载外部.js文件 [英] Unload external .js file

查看:92
本文介绍了卸载外部.js文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AJAX加载一些HTML和JS:

I'm loading some HTML and JS with AJAX:

main-page.html 加载一个名为的AJAX页面page-to-load.html

<!-- main-page.html -->
<html>
...
<script>
$.ajax({ 
  type:"POST", 
  url:"page-to-load.html", 
  success:function(data) { 
    $("#some_id").html(data);
  }
});
</script>
...
</html>

page-to-load.html 包括html和js文件:

page-to-load.html includes html and a js file:

<!-- page-to-load.html --->
<script src="scripts-for-this-html.js"></script>
<p>This is a HTML page working with above external .js file</p>

如你所见,我正在加载一个js文件, scripts-for-this -html.js

As you can see, i'm loading a js file, scripts-for-this-html.js

这完美无缺。问题是如果我再次加载(我的意思是#some_id变空并再次加载 page-to-load.html )所有脚本( scripts-for-this- html.js )保留在浏览器内存中(例如,如果我在.js文件中有一个事件,这个事件会重复多次我加载文件,即使我已经删除了脚本元素DOM)。

This works perfectly. The problem is that if I loaded again (I mean, "#some_id" gets empty and loaded with page-to-load.html again) all the script (scripts-for-this-html.js) remains in the browsers memory (for example, if I have an event in this .js file, this event gets repeated as many times I had loaded the file, even if i have deleted the script element from the DOM).

有没有办法让这项工作?我不希望一次包含所有.js文件(太多了),我想按需加载和卸载它们。

Is there any way to get this work? I don't want to include all the .js files at once (ther are too many), I want to loaded and unloaded them by demand.

推荐答案

理论上可以通过删除脚本标记来完成JavaScript卸载(就像使用 .html 一样,并消除对与脚本相关的任何对象的所有引用这涉及删除每个引用和事件监听器。即使剩下一个也可以将该变量的功能范围保留在内存中导致泄漏。

JavaScript unloading could theoretically be done by removing the script tag (as you are doing with .html and by eliminating all references to any objects associated with the script. This involves deleting every reference and event listener. Even one left could keep that variable's functional scope in memory causing a leak.

使用正则表达式删除是明智的已经加载过的脚本。(感谢@ JCOC611剥离标签的想法。)类似于:

It would be smart to use regular expressions to remove the scripts if the have been loaded already. (Credit to @JCOC611 for the idea of stripping tags.) Something like:

var usedScripts = {};

html = html.replace(/<script\s+src="([^"]+)"><\/script>/gi, function(str, file) {
    if(usedScripts[file]) {
        return "";
    } else {
        usedScripts[file] = true;
        return str;
    }
});

如果您的页数有限,我更喜欢的是一个对象:

If you have a finite number of pages, what I prefer to do is have an object:

{
    myPage: {
        html:   'myhtml.html',
        script: 'myscript.js'
    }
}

然后有一个加载器功能同时加载带有 document.createElement('script')的脚本,并使用HTML加载页面。您可以轻松检查该脚本是否已被使用并跳过加载。

Then have a loader function which simultaneously loads the script with document.createElement('script') and loads the page with HTML. You could easily check if that script has been used and skip loading.

这篇关于卸载外部.js文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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