You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SvelteKit如何禁止浏览器缓存CSS、图片及JS等资源?

在SvelteKit(Vercel部署)中禁用浏览器资源缓存的方案

你之前在+page.server.ts里用setHeaders没效果,是因为这个方法只给当前页面的HTML响应设置缓存头,而CSS、JS、图片这些静态资源是独立的请求,根本不会走页面的load函数,所以那些头对它们完全不起作用。

下面是针对所有资源(页面HTML+静态资源)禁用缓存的具体方法:

1. 使用SvelteKit Hooks拦截所有请求设置缓存头

在src/hooks.server.js(如果没有就新建)里添加以下代码,拦截所有请求,给静态资源和页面都设置强制不缓存的响应头:

// src/hooks.server.js
export async function handle({ event, resolve }) {
  const response = await resolve(event);
  
  // 匹配静态资源路径(_app是SvelteKit构建后的资源目录,后缀匹配常见静态资源)
  const isStaticAsset = event.url.pathname.startsWith('/_app/') || 
    event.url.pathname.match(/\.(css|js|png|jpg|jpeg|gif|svg|ico)$/);

  if (isStaticAsset) {
    // 设置严格的不缓存规则
    response.headers.set('Cache-Control', 'no-cache, no-store, must-revalidate');
    response.headers.set('Pragma', 'no-cache'); // 兼容HTTP/1.0
    response.headers.set('Expires', '0'); // 告诉旧浏览器立即过期
  }

  // 同时给页面HTML也设置不缓存
  response.headers.set('Cache-Control', 'no-cache, no-store, must-revalidate');
  return response;
}

2. 配置Vercel的缓存规则(关键)

因为部署在Vercel,平台默认会给静态资源设置缓存策略,可能会覆盖你在SvelteKit里设置的头,所以必须在项目根目录创建vercel.json,添加以下配置:

{
  "headers": [
    {
      "source": "/_app/(.*)",
      "headers": [
        { "key": "Cache-Control", "value": "no-cache, no-store, must-revalidate" },
        { "key": "Pragma", "value": "no-cache" },
        { "key": "Expires", "value": "0" }
      ]
    },
    {
      "source": "/(.*\\.(css|js|png|jpg|jpeg|gif|svg|ico))",
      "headers": [
        { "key": "Cache-Control", "value": "no-cache, no-store, must-revalidate" },
        { "key": "Pragma", "value": "no-cache" },
        { "key": "Expires", "value": "0" }
      ]
    },
    {
      "source": "/(.*)",
      "headers": [
        { "key": "Cache-Control", "value": "no-cache, no-store, must-revalidate" }
      ]
    }
  ]
}

这个配置会直接告诉Vercel,对所有/_app/下的构建资源、所有静态资源后缀的文件,以及所有页面都返回不缓存的头。

3. 验证效果

部署后,打开浏览器开发者工具的「网络」面板,刷新页面查看每个资源的响应头,确认Cache-Control是no-cache, no-store, must-revalidate,这样浏览器就会每次都重新请求资源,不会使用本地缓存。

⚠️ 注意:这种完全禁用缓存的方式会严重影响页面加载性能,只建议在开发调试或者特殊业务场景下使用。生产环境更合理的做法是依赖SvelteKit默认的内容哈希文件名(构建后资源文件名会带上哈希,更新后文件名变化,自动触发浏览器重新下载),配合长期缓存策略。

内容的提问来源于stack exchange,提问作者angry kiwi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 09:13:20