From 06e5ead146915abfdb2b70432842649db70497ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=89?= Date: Sun, 12 Nov 2023 18:35:36 +0800 Subject: [PATCH] Update main.js to use ServiceWorker instead of SharedWorker --- src/ServiceWorker.js | 24 ++++++++++++++++++++ src/{worker.js => SharedWorker.js} | 0 src/main.js | 36 +++++++++++++++++++----------- 3 files changed, 47 insertions(+), 13 deletions(-) create mode 100644 src/ServiceWorker.js rename src/{worker.js => SharedWorker.js} (100%) diff --git a/src/ServiceWorker.js b/src/ServiceWorker.js new file mode 100644 index 0000000..af34a23 --- /dev/null +++ b/src/ServiceWorker.js @@ -0,0 +1,24 @@ +self.addEventListener('install', function (event) { + console.log('install') + // 在安装阶段预缓存资源 + event.waitUntil( + console.log('install.waitUntil') + //caches.open('my-cache').then(function (cache) { + // return cache.addAll([ + // '/index.html', + // '/main.js', + // '/style.css' + // ]) + //}) + ) +}) + +self.addEventListener('fetch', function (event) { + console.log('fetch', event.request.url) + // 拦截网络请求并返回缓存的资源 + event.respondWith( + caches.match(event.request).then(function (response) { + return response || fetch(event.request) + }) + ) +}) diff --git a/src/worker.js b/src/SharedWorker.js similarity index 100% rename from src/worker.js rename to src/SharedWorker.js diff --git a/src/main.js b/src/main.js index b8729a5..8c795bd 100644 --- a/src/main.js +++ b/src/main.js @@ -1,15 +1,25 @@ -if (typeof SharedWorker !== "undefined") { - const worker = new SharedWorker('/src/worker.js') - worker.port.onmessage = (e) => { - console.log('worker.port.onmessage:', e.data) - } - worker.port.start() - const button = document.createElement('button') - button.innerText = 'click' - button.onclick = () => { - worker.port.postMessage('hello, worker') - } - document.body.appendChild(button) +//if (typeof SharedWorker !== "undefined") { +// const worker = new SharedWorker('/src/SharedWorker.js') +// worker.port.onmessage = (e) => { +// console.log('worker.port.onmessage:', e.data) +// } +// worker.port.start() +// const button = document.createElement('button') +// button.innerText = 'click' +// button.onclick = () => { +// worker.port.postMessage('hello, worker') +// } +// document.body.appendChild(button) +//} else { +// console.log('当前浏览器不支持 SharedWorker') +//} + +if ('serviceWorker' in navigator) { + navigator.serviceWorker.register('/src/ServiceWorker.js').then(function (registration) { + console.log('ServiceWorker registration successful with scope: ', registration.scope) + }).catch(function (err) { + console.log('ServiceWorker registration failed: ', err) + }) } else { - console.log('当前浏览器不支持webworker') + console.log('当前浏览器不支持 ServiceWorker') }