Javascript文件在Ajax导航中显示为重复 [英] Javascript files appears duplicated in ajax navigation
问题描述
我在AJAX
导航时遇到麻烦,问题在于,加载新内容之后,即使它们不再位于DOM
中,加载的javascript文件仍保留在浏览器中,它们显示为AJAX
出现时,应该替换它的javascript文件.
I´m having troubles with AJAX
navigation, the problem is that the javascript files loaded remains in the browser after the new content is loaded even they aren't in the DOM
anymore, and they appears as VM
files in the browser console and execute the code inside it. I don't want that happen because the javascript file it supposed to be replaced when the new content comes via AJAX
.
我的DOM结构是这样的:
My DOM structure is like this:
<body>
<header></header>
<main id="contentToBeReplaced">
<p>New content with its own js</p>
<script>
var script = "js/new.js";
$.getScript(script);
</script>
</main>
<footer></footer>
<script src="js/main.js"></script>
</body>
每次用自己的javascript文件加载页面时,都会出现一个新的VM
文件并保留所有较旧的文件,这就是一个问题:
Every time a page is loaded with its own javascript file appears a new VM
file and keeps all the olders, and thats a problem:
那么,问题出在哪里,我该如何解决?我需要防止重复的文件,并在加载新的js文件时将其删除.
So, whats the problem and how can I fix this? I need to prevent duplicated files and remove the js file when a new its loaded.
推荐答案
经过大量研究,我得以解决该问题.据我所知,如果不刷新页面或以编程方式清理内存浏览器的缓存,就没有绝对的方法来获取"unload"
javascript文件.
由于这些动态javascript文件中的大多数代码都与事件函数相关,因此我将事件绑定到document
而不是使用以下语法绑定到每个元素:
After many research I was able to solve the problem. As far I know there is no absolutely way to "unload"
javascript files without refresh the page, or clean the cache of memory browser programmatically.
Since most of my code inside these dynamic javascript files are related to events functions, I was binding events to the document
instead of each element with this syntax:
$(document).on("click", "#myElement", function () {
});
由于这个原因,每次加载javascript文件时,事件都会一遍又一遍地绑定,并从VM files
执行多次.当您从DOM中删除一个元素时,他的绑定事件也将被删除,除非像我一样绑定到document
.因此,我更改了on()
方法将事件直接绑定到元素:
For this reason every time the javascript file was loaded the events were binded over and over, and executed multiple times from the VM files
. When you remove an element from the DOM, his binded event it´s also removed, unless is binded to document
like mine. So I changed the on()
method to bind the event directly to the element:
$("#myElement").on("click", function() {
});
此更改后,我的问题消失了,因为我用AJAX
替换的html部分用其events
删除了该元素,而无需使用off()
手动删除绑定的事件,还有将删除的主要功能
但是, @CharlieH 在他的文章中说得很对答案.
After this change my problem has gone because the portion of html I replace with AJAX
removes that elements with its events
, without the need of use off()
to manually remove the binded events, also main functions that will be executed in multiple pages should be placed in the main js.
However, @CharlieH makes a good point in his answer.
这篇关于Javascript文件在Ajax导航中显示为重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!