worky-turkey

1.0.1 • Public • Published

worky-turkey

call functions in web worker from main thread (et vice versa)

a turkey with a safety helmet

Usage

index.html

<button type="button" id="counter"></button>
<script src="wokry-turkey.min.js"></script>
<script>
  const counterButton = document.getElementById('counter')
  const worker = workyTurkey.expose(
    {
      // the `render` function will be available in the worker
      render (value) {
        counterButton.textContent = value
      }
    },
    new Worker('worker.js')
  )

  counterButton.addEventListener('click', function () {
    // call the `increment` function exposed by the worker
    worker.increment()
  })
</script>

worker.js

loadScripts('worky-turkey.min.js')
let counter = 0;

const ui = workyTurkey.expose({
  // the `increment` function will be available in the main thread
  increment(value = 1) {
    counter += value
    // call the `render` function exposed by the ui thread
    ui.render(counter)
  }
});

// call the `render` function exposed by the ui thread
ui.render(counter)

Browser support

worky-turkey uses proxies, whose are supported in all evergreen browsers: caniuse proxy

But...

What's about Comlink?

worky-turkey is heavily inspired by Comlink. But there are use cases, you just don't need the super power of Comlink.

Comparend to Comlink, worky-turkey...

  • only supports function calls
  • does not return anything (just fire and forget)
  • does not support callbacks as function parameter (just Transferables. As rule of thumb: only use primitives, plain objects and arrays as parameter)
  • is written in less than 25 lines of code 😎 (~300 bytes minified, ~240 bytes gzipped)

This is great if you just want the other side know, that something has to be done.
This is not so great if you rely on the result of the other sides function call.

Why do I need a library for this simple task?

Of course, you can postMessage something like { fn: 'doSomething', params: ['foo', 42] } and handle it accordingly on the other side, but it simply feels more naturally to call worker.doSomething('foo', 42).

Readme

Keywords

none

Package Sidebar

Install

npm i worky-turkey

Weekly Downloads

0

Version

1.0.1

License

Unlicense

Unpacked Size

6.43 kB

Total Files

7

Last publish

Collaborators

  • lokkasio