For bundlejs.com, and astro.build/play, I found that I needed a way to use SharedWorkers reliably on all browsers, so, I decided to make a miniature script that would act as a wrapper around the SharedWorker class, by default it would try to create a SharedWorker but if unssuported it would otherwise switch to normal web workers this makes, SharedWorkers a type of progressive enhancement.
When I realized that a polyfill/ponyfill doesn't exist for SharedWorkers I realized I needed to make one, and to ensure reliable that the polyfill was thoroughly vetted and tested for cross browser compatibility, so, I made @okikio/sharedworker.
Usage
@okikio/sharedworker is a small mostly spec. compliant polyfill/ponyfill for SharedWorkers, it acts as a drop in replacement for normal Workers, and supports a similar API surface that matches normal Workers.
You use it like this,
shared-worker.js
const start = (port) => {
port.onmessage = ({ data }) => {
if (data == "Hey")
port.postMessage("Hello, from the SharedWorker.");
};
};
self.onconnect = e => {
let [port] = e.ports;
start(port);
};
if ("SharedWorkerGlobalScope" in self)
start(self);
main.js
import SharedWorker from "@okikio/sharedworker";
const sharedworker = new SharedWorker(new URL("shared-worker.js", import.meta.url));
sharedworker.onmessage = ({ data }) => {
console.log(data);
};
sharedworker.postMessage("Hey");
In the cases of bundlejs.com and astro.build/play, @okikio/sharedworker was used for esbuild as well as the monaco-editors editor and typescript workers. @okikio/sharedworker was used as a separate utility file for easy access.
Limitation
The major limitation with @okikio/sharedworker is that on browsers that don't natively support SharedWorker, you can't use @okikio/sharedworker as an across tab communication tool. But for everything else it's feature parity and spec. compliance should be great.
Conclusion
So, will you use it? Tell me below, or say Hi on twitter.
Image from Tengyart on Unsplash.