worker-module

0.0.2 • Public • Published

Worker Module

Usage

To be used in the browser with a module bundling system, like browserify.

var myModule = require('./my-worker'),
    myWorker = require('worker-module')(myModule)();

Full example

my-worker.js:

module.exports = function(){
    "use strict";
 
    function onmessage(e) {
        postMessage('Hello ' + e.data);
    }
}

Main JS:

var myModule     = require('./my-worker'),
    createWorker = require('worker-module')(myModule),
    worker1      = createWorker(),
    worker2      = createWorker();
 
myWoker1.onmessage = function(e) {
    console.log('Message received from worker 1: ' + e.data);
}
myWoker2.onmessage = function(e) {
    console.log('Message received from the second worker: ' + e.data);
}
 
worker1.postMessage('World!');
worker2.postMessage('Something Else');

Why

Web workers need a URL to a script in order to run it. This results in an extra request to the server, and goes against our efforts to concatenate all scripts and work in a single, clean, modular way.

How it works

The script behind this is tiny, so take a look. It uses the blob method; a blob is created for the module, the url of which is passed to the worker constructor.

Compatibility

IE Edge Firefox Chrome Safari Android
10 Yes Yes Yes Yes 5

License

This project is licensed under the ISC License - see the LICENSE.md file for details

Dependencies (0)

    Dev Dependencies (0)

      Package Sidebar

      Install

      npm i worker-module

      Weekly Downloads

      2

      Version

      0.0.2

      License

      ISC

      Last publish

      Collaborators

      • dlevs