有没有一种方法可以让我把一些代码放在我的页面上,这样当有人访问一个网站时,它就会清空浏览器缓存,这样他们就可以查看更改了?

使用语言:ASP。净,VB。NET,当然还有HTML, CSS和jQuery。


当前回答

很多答案都忽略了一点——大多数开发人员都很清楚关闭缓存是低效的。然而,在许多常见的情况下,效率并不重要,默认缓存行为被严重破坏。

这些包括嵌套的、迭代的脚本测试(大的一个!)和坏的第三方软件变通方法。这里给出的解决方案都不足以解决这种常见场景。大多数web浏览器都有过于激进的缓存,并且没有提供合理的方法来避免这些问题。

其他回答

<meta http-equiv="pragma" content="no-cache" />

参见https://stackoverflow.com/questions/126772/how-to-force-a-web-browser-not-to-cache-images

这是我在一个使用PHP的应用程序中使用的简单解决方案。

所有JS和CSS文件都放在一个有版本名的文件夹中。示例:"1.0.01"

root\1.0.01\JS
root\1.0.01\CSS

在那里创建一个Helper并定义版本号

<?php
function system_version()
{
    return '1.0.07';
}

和链接JS和SCC文件如下

<script src="<?= base_url(); ?>/<?= system_version();?>/js/generators.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="<?= base_url(); ?>/<?= system_version(); ?>/css/view-checklist.css" />

每当我对任何JS或CSS文件进行更改时,我都会在Helper中更改System Verson并重命名文件夹并部署它。

如果有兴趣,我已经找到了我的解决方案,让浏览器在。net MVC (.net fw 4.8)和使用包的情况下刷新.css和.js。 我想让浏览器仅在部署新程序集之后刷新缓存文件。

根据撒利亚多尼的回答,我的解决方案如下:

store your application base url in the web config app settings (the HttpContext is not yet available at runtime during the RegisterBundle...), then make this parameter changing according to the configuration (debug, staging, release...) by the xml transform In BundleConfig RegisterBundles get the assembly version by the means of reflection, and... ...change the default tag format of both styles and scripts so that the bundling system generates link and script tags appending a query string parameter on them.

下面是代码

public static void RegisterBundles(BundleCollection bundles)
{
   string baseUrl = system.Configuration.ConfigurationManager.AppSettings["by.app.base.url"].ToString();
       
   string assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
   
   Styles.DefaultTagFormat = $"<link href='{baseUrl}{{0}}?v={assemblyVersion}' rel='stylesheet'/>";
   Scripts.DefaultTagFormat = $"<script src='{baseUrl}{{0}}?v={assemblyVersion}'></script>";
}

你会得到这样的标签

<script src="https://example.org/myscriptfilepath/script.js?v={myassemblyversion}"></script>

您只需要记住在部署之前构建一个新版本。

Ciao

除了设置Cache-control: no-cache,如果你想每次刷新本地副本,你还应该将Expires头设置为-1(某些版本的IE似乎需要这样做)。

查看HTTP缓存-与服务器检查,始终发送If-Modified-Since

有一个小技巧可以使用。诀窍是在脚本标记中向文件名附加一个参数/字符串,并在文件更改时更改它。

<script src=“myfile.js?version=1.0.0”></script>

浏览器将整个字符串解释为文件路径,即使“?”后面的是参数。所以现在发生的是,下次当你更新你的文件时,只要改变你网站上script标签中的数字(示例<script src="myfile.js?version=1.0.1"></script>),每个用户的浏览器都会看到文件已经改变,并抓取一个新的副本。