在CSS文件的URL末尾添加查询字符串,然后在每次需要更新样式表时更新该查询字符串即可。示例如下:
在HTML中引用CSS文件的代码:
在Blazor组件中定义一个CacheBusting服务:
public class CacheBustingService
{
public string GetCacheBuster()
{
return Guid.NewGuid().ToString().Replace("-", "");
}
}
在组件中注入CacheBusting服务:
@inject CacheBustingService CacheBuster
在需要更新样式表的事件(例如点击按钮)中使用CacheBuster服务来获取新的缓存破坏字符串并更新样式表的URL:
@code {
private string _cacheBuster;
private void UpdateStyles()
{
_cacheBuster = CacheBuster.GetCacheBuster();
StateHasChanged();
}
private string _styleUrl => $"css/site.css?v={_cacheBuster}";
}
最后,在HTML中引用使用缓存破坏的CSS文件: