Created
June 5, 2020 06:22
-
-
Save bellbind/839b32d5d6fb684eb3d2e10fcfc2201c to your computer and use it in GitHub Desktop.
[browser]SharedWorker example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<script type="module"> | |
const worker = new SharedWorker("./worker.js"); | |
worker.port.addEventListener("message", ev => { | |
document.body.textContent = `connected: ${ev.data}`; | |
}); | |
worker.port.start(); // spawm connect event to a shared worker | |
</script> | |
</head> | |
<body></body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// shared state for each script url | |
// - reset after all page closed (all ServiceWorker instance terminated) | |
let counter = 0; | |
this.addEventListener("connect", ev => { | |
counter++; | |
const port = ev.ports[0]; // port of each ServiceWorker instances | |
port.postMessage(counter); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
demo: https://gist.githack.com/bellbind/839b32d5d6fb684eb3d2e10fcfc2201c/raw/index.html
(open multiple pages to check these counters)