"Multiple instances of JavaScript files seem to be present when using Ajax navigation

Having some difficulties with AJAX navigation. The issue is that the JavaScript files loaded remain in the browser even after the new content is loaded, even when they are no longer in the DOM. These files appear as VM files in the browser console and continue to execute their code. This is not desired behavior as the JavaScript file should be replaced when new content is fetched via AJAX.

The structure of my DOM looks 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>

Each time a page loads with its respective JavaScript file, a new VM file appears and retains all the older ones, causing issues:
https://i.stack.imgur.com/iNJFv.png

What could be causing this problem and how can it be resolved? I need to prevent duplicate files and remove the existing JavaScript file when a new one is loaded.

Answer №1

Every unique entry within the Javascript global execution context is able to represent either a single object or variable. When the same function is repeatedly loaded into the global context, it replaces the function code each time.

It's important to ensure that scripts being lazy-loaded are managed in a way that they correspond to the same entry within your global context (or framework).

Take a look at the following sample JavaScript codes that 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');
             {

If you load script one and execute dynFun(), it will output "Loaded early". Then, if you load the second script and run dynFun() again, it will display "Loaded late".

However, if these functions involve automatic processes like setTimeout, they will continue to operate until the page is closed.

In such cases, dynamic scripts should first perform some cleanup:

var timeTracker; // This is a global variable

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

                   timeTracker = setTimeout(someFn, 1000)   
             {

Keep in mind - in garbage-collected languages like JS, you cannot directly deallocate memory. You can only manipulate references to objects to trick the clean-up process.

Answer №2

Through extensive research, I managed to successfully resolve the issue at hand. To my knowledge, there is no foolproof method to "unload" javascript files without having to refresh the page or manually clear the browser's memory cache.
Most of the code within these dynamic javascript files pertains to event functions, so I opted to bind events to the document rather than each individual element using the following syntax:

$(document).on("click", "#myElement", function () {

});

Consequently, every time the javascript file was loaded, the events were repeatedly bound and executed multiple times from the VM files. When an element is removed from the DOM, its bound event is also removed unless it is bound to the document like in my case. Thus, I modified the on() method to directly bind the event to the element:

$("#myElement").on("click", function() {

});

This adjustment effectively resolved my issue as the HTML portion replaced with AJAX removes those elements along with their associated events, eliminating the necessity for utilizing off() to manually remove the bound events. Moreover, essential functions that are meant to be executed across multiple pages should be housed in the main js script.
Nevertheless, @CharlieH raises a valid point in his response.

Answer №3

To ensure that the "new.js" file can be tracked in Chrome Dev Tools, include the following line at the beginning of the file:

//# sourceURL=new.js

Answer №4

To enhance the security of your JavaScript code, consider including 'use strict'; at the beginning of your file. This will activate a stricter parsing mode that helps prevent unintentional global variables. If you're still facing issues, check out this informative article on "garbage collector" and learn more about preventing memory leaks in JavaScript: "4 Types of Memory Leaks in JavaScript and How to Get Rid Of Them"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The function setEmail is not defined. (In 'setEmail(input)', 'setEmail' is not recognized) (Cannot utilize hooks with context API)

App.js const[getScreen, showScreen] = useState(false); const[getEmail, setEmail] = useState(""); <LoginScreen/> <LoginContexts.Provider value={{getEmail,setEmail,getScreen,showScreen}}> {showScreen?<Screen2/>:<LoginScre ...

Using jQuery to target a specific item from a retrieved list of elements

I'm currently working on a photo gallery feature that is reminiscent of Instagram or Facebook user photos. My goal is to enable users to view details about each image (such as the date) in a box that appears over the image when they hover over it. E ...

The div is unable to display data retrieved from the php file using Ajax

This is the function utilizing ajax $(document).ready(function() { $('#submit').click(function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: 'searchphp.php&apo ...

Adjust CSS classes as user scrolls using skrollr

I am currently facing an issue with the prinzhorn/skrollr plugin when trying to use removeClass/addClass on scroll function. I have attempted to find a solution but unfortunately, nothing has worked for me. <li class="tab col s3"><a data-800="@cl ...

The list marquee in HTML, JS, and CSS is not being properly rendered on

I recently made changes to a code that showcases a marquee scrolling a basic HTML list. Check it out here: I am facing 3 issues that I am struggling to resolve: JS: I want the marquee to continuously show text re-entering from the right just after it ...

issue with mark.js scrolling to selected sections

Our document searching functionality utilizes mark.js to highlight text and navigate to the results. You can see an example of this in action here. If you search for "Lorem ipsum" -> the highlighting works perfectly, but the navigation jumps to fragments ...

"Concealing Querystrings in Node.js and AJAX: A Step-by-Step

I want to create a simple login form using the ajax Post method. However, I am having issues with the querystring still appearing in the URL. Can anyone help me resolve this issue? Thank you for any assistance! [ https://i.stack.imgur.com/R76O4.png http ...

How to simultaneously play a sound and display an alert message using JavaScript

My JavaScript code attempts to play a sound and then display an alert, but the alert always shows up first. When I click 'ok', the sound plays. How can I make it so that the sound plays before the alert appears? <script> function play() { ...

Monitoring user logins based on user identification

How can I effectively monitor the activity of users who have logged into a web application that is managed by an external company? Despite my extensive research efforts, as a non-technical individual, I am struggling to understand how to utilize Google Ana ...

The use of callbacks is ineffective in addressing the asynchronous nature of

Hello everyone, I'm currently working on a weather app and I'm facing an issue with the asynchronous behavior of useState. I've come across some suggestions on Stack Overflow that using a callback in the useState function might solve the pro ...

the dropdown menu toggle is not working as expected

My dropdown icon is not appearing and the menu options are not functioning properly. Despite trying to use a script to display the text when an option is clicked, it doesn't seem to be working. It appears that the toggle functionality is not working ...

The WebApi endpoint is not being accessed when deployed on the IIS server, even though it functions properly on the local host

Issue with Web API Endpoint not being triggered after deploying solution to IIS server Working endpoint : https://localhost:44335/Api/Course/GetStudents Endpoint not functioning correctly: Ajax Code function GetStudents(IsEdit) { $.ajax({ ...

Mastering the Art of Tab Selection with Jquery

I am trying to implement a tabs control using jQuery. Here is the HTML code I have: <div id="tabs" class="news1"> <ul> <li><a href="#tabs-1">Track</a></li> <li><a href="#tabs-2">History&l ...

Concealing div containers and eliminating gaps

Looking for a way to filter div boxes using navigation? Check this out: <ul> <li><a href="javascript:void(0);" data-target="apples">Appels</a></li> <li><a href="javascript:void(0);" data-target="bananas">Ban ...

Enhance your search experience with AJAX-powered search boxes

I need to implement multiple textboxes on my webpage, each with its own search query to retrieve data from the database. While I have successfully implemented this for one textbox, I am facing difficulties getting it to work for two or more textboxes. He ...

Data structure for Highcharts:

Recently, I've been experimenting with Highcharts (http://www.highcharts.com) in a test application built on rails 3.1.1 and HAML. As someone who is still new to JavaScript, I'm striving towards achieving a seamless integration of Highcharts. Wi ...

Struggling to implement JQuery code in a Next.js application

I'm having trouble getting my tracking code to work in Next.js. <Script> window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments) } gtag('js', new Date()) ...

Please do not exceed two words in the input field

I need to restrict the input field to only allow up to two words to be entered. It's not about the number of characters, but rather the number of words. Can this restriction be achieved using jQuery Validation? If not, is there a way to implement it u ...

What is the technique of passing objects using jQuery's ajax function?

I'm trying to send an object to a controller action, but it's not working. The object is null with no errors. I've debugged it and confirmed that the parameters are being passed correctly. scripts $(document).ready(function () { var Irregu ...

Establishing a distinct registry for a particular package within the .npmrc configuration file

Today, I encountered a new challenge that I've never faced before. I am currently in need of having private node packages published in both a private and public repository under the same @scope. The packages on npmjs.org are stable and open to the pu ...