Update main.js to use ServiceWorker instead of

SharedWorker
This commit is contained in:
2023-11-12 18:35:36 +08:00
parent c4db8b5e1e
commit 06e5ead146
3 changed files with 47 additions and 13 deletions

24
src/ServiceWorker.js Normal file
View File

@ -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)
})
)
})

View File

@ -1,15 +1,25 @@
if (typeof SharedWorker !== "undefined") { //if (typeof SharedWorker !== "undefined") {
const worker = new SharedWorker('/src/worker.js') // const worker = new SharedWorker('/src/SharedWorker.js')
worker.port.onmessage = (e) => { // worker.port.onmessage = (e) => {
console.log('worker.port.onmessage:', e.data) // console.log('worker.port.onmessage:', e.data)
} // }
worker.port.start() // worker.port.start()
const button = document.createElement('button') // const button = document.createElement('button')
button.innerText = 'click' // button.innerText = 'click'
button.onclick = () => { // button.onclick = () => {
worker.port.postMessage('hello, worker') // worker.port.postMessage('hello, worker')
} // }
document.body.appendChild(button) // 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 { } else {
console.log('当前浏览器不支持webworker') console.log('当前浏览器不支持 ServiceWorker')
} }