'use strict' // 配置 const pwaCdnConfig = { cdnUrl: 'https://cdn.fillcode.com/', serviceWorkerUrl: '/__static/sw-cdn.js', staticRegex: /\.(js|css|png|jpg|jpeg|gif|svg|webp|woff|woff2|ttf|ico)$/, debug: false, } /** * PWA 初始化函数 */ async function initializePWA() { // 检查支持 if (!('serviceWorker' in navigator)) return console.log('PWA-CDN: Service Worker not supported') let registration; try { // 注册Service Worker - 使用相对路径 registration = await navigator.serviceWorker.register(pwaCdnConfig.serviceWorkerUrl, {scope: '/'}) console.log('PWA-CDN: Service Worker registered') } catch (error) { console.error('PWA-CDN: Failed to register Service Worker:', error) } // 发送初始配置 const sendConfig = () => { registration.active.postMessage({type: 'CONFIG', config: pwaCdnConfig}) } // 如果注册失败,直接返回错误 if(!registration) return console.error('PWA-CDN: Service Worker registration failed, cannot send config') // 更新配置函数 window.updatePWACDNConfig = (newConfig) => { Object.assign(pwaCdnConfig, newConfig) sendConfig() } // 等待Service Worker激活后发送配置 if (registration.active) sendConfig() // 监听Service Worker更新事件 registration.addEventListener('updatefound', () => { const newWorker = registration.installing newWorker.addEventListener('statechange', () => { if (newWorker.state === 'activated') sendConfig() }) }) } /** * 启动 PWA-CDN * */ initializePWA().catch(console.error)