Workerit library

NPM library for executing any javascript function from within a Web Worker.

Workerit

Workerit tries to simplify the way we write code for Web Workers. No need to create a specific file for it anymore.

With workerit, you only need to create a workerit instance and call the method .install(function) passing the the function to be run in a Web Worker.

/*
 * Install a function into the worker.
 *
 * Note: The installed function should have a **scope** as first parameter.
 *       This is the DedicatedWorkerGlobalScope scope that run with the Worker.
 */
workerit.install(function (scope, event) {

  /*
   * scope is the DedicatedWorkerGlobalScope instance.
   *
   * With it you can invoke methods as you would do with DedicatedWorkerGlobalScope.
   * For example:
   *
   *    // Let´s communicate with the main thread
   *    scope.postMessage('hola')
   *
   */

  /*
   * More code to execute inside the Web Worker.
   */

})

To execute the function in the Web Worker_, invoke the _postMessage(object) method with the needed data for your function.

Workerit will run your function inside a Web Worker.

Let’s see an example of how to use this library:

/* ******************************
 *
 *  Main Thread code
 *
 ********************************/


/*
 * workerit wraps Web Worker and add an extra method .install(Function).
 */
const workerit = new window.Workerit()

/*
 * Listen messages web worker sends to main thread
 */
workerit.addEventListener('message', function (evt) {
  console.log('Message = ' + evt.data)
})

/*
 * Install a function into the web worker.
 */
workerit.install(function (scope, event) {

 /* ******************************
  *
  *  Web Worker Thread code
  *
  *********************************/

  let res = 0
  for (let i = 0; i <= event.data; i++) {
    for (let j = 0; j <= event.data; j++) {
        res += i
    }
  }

  /*
   * Lets sent the result back.
   */
  scope.postMessage(res)
})

/*
 * First message will start the Worker.
 */
workerit.postMessage(5000)

Inspired by the work done in the following libraries: