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

Angular Service Worker刷新时出现504(网关超时)错误

解决Service Worker刷新时504超时问题

1. 优化Service Worker更新逻辑

注册SW时主动监听更新事件,避免浏览器默认等待机制导致的阻塞:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', async () => {
    const registration = await navigator.serviceWorker.register('/sw.js');
    
    // 监听SW更新
    registration.addEventListener('updatefound', () => {
      const newWorker = registration.installing;
      newWorker.addEventListener('statechange', () => {
        if (newWorker.state === 'installed') {
          if (navigator.serviceWorker.controller) {
            // 通知新SW跳过等待,立即激活
            newWorker.postMessage({ type: 'SKIP_WAITING' });
          }
        }
      });
    });
  });
}

同时在SW脚本中添加skipWaiting监听:

// sw.js
self.addEventListener('message', (event) => {
  if (event.data?.type === 'SKIP_WAITING') {
    self.skipWaiting();
  }
});

新SW安装完成后会立即激活,避免旧SW占用资源引发请求超时。

2. 调整缓存策略,避免过期资源阻塞

在fetch事件中优化缓存逻辑,避免长期缓存未更新的资源:

// sw.js 中的fetch处理
self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request)
      .then((response) => {
        // 返回缓存的同时后台更新缓存
        if (response) {
          fetch(event.request).then((newResponse) => {
            caches.open('your-cache-v1').then((cache) => {
              cache.put(event.request, newResponse);
            });
          });
          return response;
        }
        // 无缓存直接请求网络,失败则返回降级页面
        return fetch(event.request).catch(() => caches.match('/offline.html'));
      })
  );
});

避免cache-first策略滥用,防止SW拦截请求后返回过期内容触发网关超时。

3. 激活时清理旧缓存与SW

在SW激活阶段主动清理旧缓存并接管所有页面:

// sw.js 激活事件
self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      // 删除旧缓存
      return Promise.all(
        cacheNames.filter(name => name !== 'your-cache-v1')
          .map(name => caches.delete(name))
      );
    }).then(() => {
      // 立即控制所有打开的页面
      return self.clients.claim();
    })
  );
});

消除新旧SW共存导致的请求冲突问题。

4. 配置服务器SW脚本缓存规则

确保服务器对sw.js设置严格的缓存控制头,强制浏览器每次检查更新:

Cache-Control: no-cache, no-store, must-revalidate

避免浏览器使用本地缓存的旧SW脚本引发异常。


内容的提问来源于stack exchange,提问作者Ashwani Tandon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 07:47:05