Search code examples
javascriptjqueryasp.net-mvcbrowser-cache

How to Prevent Javascript code runing multiple times caused by caching


I have an Asp.net-MVC that when I send the request it returns a partial-view.

public ActionResult AccountDetails()
{
    return PartialView("~/Views/partials/Account/Details.cshtml");
}

Then I load partial in my form using code below.

var condition = true;
var pageNumber = 0;
for (var i = 1; i < 10; i++) {
    $("#page_view" + i).addClass("d-none");
    if (condition && $("#page_view" + i).html().trim() == "") {
        pageNumber = i;
        condition = false;
    }
}
$("#page_view" + pageNumber).removeClass("d-none");

$.ajax({
    url: url,
    type: "GET",
    async: true,

    success: function (result) {
        $("#page_view" + pageNumber).html(result);
    }
});

In my main html file I just use a link to get the page and load it:

<a href="javascript: load_main_form('Account/Details');">DetailsPage</a>

In this method the problem is when I load and close one page multiple times Javascript of that page stores in cache by every load and some functions or events runs multiple times by every load.

I used ajaxComplete to get how many times it store it in cache.

How can I clear cache or rewrite on last one? Or even if there is a faster way to do this I will be thankful for sharing.


Solution

  • I'm gonna address your question in steps

    1. "Javascript code runing multiple times caused by caching"

    Cache does not cause code to run multiple times. Cache just affects how the code is loaded. If you attempt to load a js multiple times, cache will just affect where the browser is going to look for that file, either the web (if not cached) or the local cache. Your browser will never run any code just because is in the cache, it will run because you requested it to do (intentionally or unintentionally)

    Most probably there is javascript code meant to run once inside of one of those views that you are loading. So if you have code meant to run once, it must be placed in the file that loads the rest of the views (usually called the layout, or the base)

    Any javascript present in any of the views, must be specific for that view. So in order to debug that, go to any view causing issues and see if the javascript is there, if so, search the origin (maybe from the layout, maybe another partial view inside that partial view, or somwhere)

    See the image below to understand what I mean enter image description here

    Now finally

    2. "How to Prevent Javascript code runing multiple times"

    Yes, you can prevent code running multiple times, Ill explain how, but I advise you to first fix the structure of your proyect and only use this in the cases where structure cannot change, as otherwise it would be like puting paint on top of the cracks

    lets say that you have some code:

    let myCounter = 0;
    myCounter ++;
    console.log(`Hey! I've run ${myCounter} times`);
    

    then inside the partial view, change the code and wrap it in a function together with a statement that checks if that has already run (you give it a name, lets say initializator, and then...)

    !window.initializator && (initializator = true) && (function() {
        let myCounter = 0;
        myCounter++;
        console.log(`Hey! I've run ${myCounter} times`);
    })()
    

    now, no matter how many times the browser executes this fragment of code, it will never run the instructions inside more than once, because it leaves a variable in the global scope that ensures that if the code is executed again, the code will be skipped.

    You can also use another object instead of window (which I highly recommend, because you must never use global variables if you can avoid them) but I put the example like that because of if you don't have control of the flow of your code, you cannot ensure to have an object instantiated before either.