Worker that Works in All Environments, including Internet Explorer.
npm install universal-worker:warning: this library is under active development and breaking changes are expected
---------
bash
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 NodeJSlimitations
- No Support for importScripts outside the Browser
- import syntax runs as is without fallback conversion, in the browsersupported API
- new Worker(aURL, options)
- worker.postMessage(msg)
- worker.terminate()
- worker.onmessage
- worker.onerrorusage
loading
You can load the universal-worker in several ways:
#### CommonJS Require
`javascript
const { Worker } = require("universal-worker");
`
#### JavaScript Modules
`javascript
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.
`html
`creating the worker
`javascript
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
$3
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.
`javascript
onmessage = event => {
const { data } = event;
const result = Math.pow(data, 2);
const transferList = undefined;
postMessage(result, transferList);
};
`
$3
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.
`javascript
module.exports = data => Math.pow(data, 2);
`$3
If you export your function using, export syntax, universal-worker will automatically pass a message onto the default export
`javascript
export default function square (data) {
return Math.pow(data, 2);
});
``