简体   繁体   English

如何防止缓存导致的Javascript代码多次运行

[英]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 .我有一个Asp.net-MVC ,当我发送请求时它返回一个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:在我的主 html 文件中,我只使用一个链接来获取页面并加载它:

<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.在这种方法中,问题是当我多次加载和关闭一个页面时,该页面的 Javascript 每次加载都存储在缓存中,并且某些函数或事件每次加载都会运行多次。

I used ajaxComplete to get how many times it store it in cache.我使用ajaxComplete来获取它在缓存中存储的次数。

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.或者即使有更快的方法来做到这一点,我也会感谢您的分享。

I'm gonna address your question in steps我会分步骤回答你的问题

1. "Javascript code runing multiple times caused by caching" 1.“缓存导致的Javascript代码多次运行”

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.如果您尝试多次加载一个 js,缓存只会影响浏览器查找该文件的位置,web(如果未缓存)或本地缓存。 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.很可能有 javascript 代码意味着在您正在加载的其中一个视图中运行一次。 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)因此,如果您有打算运行一次的代码,则必须将其放置在加载 rest 视图(通常称为布局或基础)的文件中

Any javascript present in any of the views, must be specific for that view.任何视图中出现的任何 javascript 都必须特定于该视图。 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)因此,为了调试 go 到任何导致问题的视图,并查看 javascript 是否存在,如果是,请搜索原点(可能来自布局,可能是该局部视图内的另一个局部视图,或某处)

See the image below to understand what I mean请参阅下图以了解我的意思在此处输入图像描述

Now finally现在终于

2. "How to Prevent Javascript code runing multiple times" 2.《如何防止Javascript代码多次运行》

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...)然后在部分视图中,更改代码并将其包装在 function 中,并附上一条检查它是否已经运行的语句(你给它一个名字,让我们说初始化器,然后......)

!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.现在,无论浏览器执行多少次这段代码,它都不会多次运行里面的指令,因为它在全局 scope 中留下了一个变量,确保如果代码再次执行,代码将被跳过.

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.您也可以使用另一个 object 而不是 window(我强烈推荐,因为如果可以避免,您绝不能使用全局变量)但我这样举这个例子是因为如果您无法控制代码流,您不能确保在任何一个之前实例化 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM