Javascript files appears duplicated in ajax navigation

假装没事ソ 提交于 2019-12-10 14:22:37

问题


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.

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>

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:

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.


回答1:


Each unique entry in Javascript global execution context can only represent a single object or a variable. The repeated loading of the same function to the global context will replace the function code again and again.

You should manage the scripts being lazy-loaded in such a way that they represent the same entry in your global context (or the framework you use)

Look at the following sample js codes which are assumed to be lazy loaded at two different times

//script 1

var dynFun = function() {
                console.log('Loaded early');
             {



//script 2
var dynFun = function() {
                console.log('Loaded late');
             {

Now if you load the script one and execute dynFun(), it will log out "Loaded early". Now, at this point, if you load second script and execute dynFun() again, it will log out "Loaded late" .

However, if each of these functions initiate automatic processes like setTimeout, they will continue to function until the page is closed.

In such occasions, your dynamic scripts should first do some clean up first.

var timeTracker;   //This is global

var dynFun = function() {
                  if (timeTracker)
                      clearTimeout(timeTracker)

                   timeTracker = setTimeout(someFn, 1000)   
             {

Remember - you cannot get to decide deallocation of memory in garbage-collected languages like JS. You can only trick the clean up process by manipulating references to the objects.




回答2:


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 () {

});

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() {

});

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.




回答3:


Add this at the begining of the "new.js" file to track that file in Chrome Dev Tools:

//# sourceURL=new.js



回答4:


Add 'use strict'; at the top of you JavaScript file it will enable a stricter mode of parsing JavaScript that prevents accidental globals. if it doesn't help you can read more about "garbage collector" in this article "4 Types of Memory Leaks in JavaScript and How to Get Rid Of Them"



来源:https://stackoverflow.com/questions/56851456/javascript-files-appears-duplicated-in-ajax-navigation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!