Krzysztof Kaczor

Passionate Software Developer

Webworkify - use browserify and web workers together

on 25. June 2015

Browserify is an awesome tool that lets you run your NodeJS app in browser. It captures whole dependency tree of your app and bundles everything into a single .js file which can be included directly by browser. It cares about providing custom implementation for NodeJS specific classes like buffers and you can even use additional transforms like brfs to inline file contents into bundles.

Recently, during work on my own chess AI I wanted to add web workers support because running AI algorithms froze whole browser. I have already used Browserify in that project. Web workers run in separate context that your website and to create them you need pass URL (or string using URL.createObjectUrl) to it’s definition which doesn’t play nice with Browserify.

After googling for some time I came upon Webworkify. I think that name is self-explanatory - it enables Browserify to work with web workers. Here’s quick demo.

First, let’s create web worker. It will be painfully simple:

var counter = 0;
var WAIT = 100000000;

module.exports = function (self) {
  while(true) {
      for(var i = 0;i < WAIT;i++);

      self.postMessage(counter++);
  }
};

and here’s a runner:

var worker = require('webworkify')(require('./dummyWorker.js'));
worker.addEventListener('message', function (ev) {
 console.log(ev.data);
});

Thanks to web workers even though we are pointlessly looping in our code, browser will still be fully responsive and thanks to Webworkify we can require in our code other modules - everything will be bundled together and Webworkify will take care of creating web workers using URL.createObjectUrl and Blob of javascript code.