Make multithreading easier with Inline Web Workers

Danny Blue
2 min readJun 4, 2016

--

Web Workers are awesome, and yet somehow they are not nearly as widely used despite their pretty good browser support (IE10 and up). One reason for that is maybe they don’t find into your normal development flow and build setup.

First up a quick refresher. A web worker is a new OS level thread that is spun up by your browser. This allows the developer to run code without blocking the main UI thread. You communicate with the worker via the post message api. For information on web workers you can view it here.

We can use web workers to prevent things like below.

Now let’s take a look at a standard web worker.

Not bad right? We can now offload any logic we want to a separate thread and keep the UI thread unblocked. COOL! But, maybe maintaining these separate worker files is a pain or just doesn’t fit with how we are writing out code. Wouldn’t it be nice if you could just do this?

Enter inline web workers! Inline web workers allow you to create a web worker from a function that you give it. To get inline workers to work we have to rely on two other technologies, blobs and object urls. Let’s take a look at the createWorker function and see what is in its guts.

Thats it! A three line function will let you spin up web workers with no need to maintain separate files, but let’s dissect it and find out what it means.

var blob = new Blob(['self.onmessage = '], fn.toString()], { type: 'text/javascript'});

This line create a new Blob of data that we are telling it is javascript. You can read up on blobs here.

var url = URL.createObjectURL(blob);

Now we still need a url for the worker to use. Can get one dynamically by using the URL.createObjectUrl method. We can pass our freshly minted blob into it and it will give use a url. Now we can use our new object url to create a web worker and we are off to the races.

Now that we can see how easy it is to create this helper function we can go off and add whatever other abstractions we would like, Even something using promises like so.

If you want to see the source code for that you can view it here.

--

--

Danny Blue
Danny Blue

Written by Danny Blue

Lead Software Engineer @DeloitteDigital. Google Developer Expert for web technologies. Co-host on @TheWebPlatform podcast. making computers do things