universal-worker

Worker that Works in All Environments, including Internet Explorer.

Usage no npm install needed!

<script type="module">
  import universalWorker from 'https://cdn.skypack.dev/universal-worker';
</script>

README

:warning: this library is under active development and breaking changes are expected


universal-worker: beta

Worker that Works in All Environments, including Internet Explorer.

install

npm install universal-worker

features

  • Converts import to require for NodeJS Worker Threads
  • Works in Internet Explorer with Frame Worker
  • Automatically Wrap Files with Worker Events
  • Works with Webpack
  • Supports Data URLs and File URLs
  • Use Web Worker API in NodeJS

limitations

  • No Support for importScripts outside the Browser
  • import syntax runs as is without fallback conversion, in the browser

supported API

usage

loading

You can load the universal-worker in several ways:

CommonJS Require

const { Worker } = require("universal-worker");

JavaScript Modules

import { Worker } from "universal-worker";

Script Tag in the Browser

When you load universal worker via a script tag, it will check if Worker is fully supported (including transfers). If not, it will polyfill Worker with a "FrameWorker" that fakes a Web Worker by running the worker script in an iframe.

<script src="https://unpkg.com/universal-worker"></script>

creating the worker

const worker = new Worker("./path/to/worker.js");

inside the worker.js file

You can define your worker in three different ways: (1) events, (2) module.exports = function, and (3) export default function

using Web Worker Events

You can define your worker using Web Worker events. When run on NodeJS, universal-worker will automatically polyfill these web worker events, so your worker script will automatically use the worker_threads API without having to create a separate worker file.

onmessage = event => {
  const { data } = event;
  const result = Math.pow(data, 2);
  const transferList = undefined;
  postMessage(result, transferList);
};

using module.exports

If you don't define an onmessage event in your worker script, universal-worker will automatically look for module.exports and assume that a message should be sent as an argument to this function.

module.exports = data => Math.pow(data, 2);

using export default function

If you export your function using, export syntax, universal-worker will automatically pass a message onto the default export

export default function square (data) {
  return Math.pow(data, 2);
});