Load Web Workers Without A JavaScript File

Ever want to load a JavaScript Web Worker without specifying an external JavaScript file? There are a couple of different ways to do this by creating a blob and object URL - I wrapped this functionality up into a little plugin to share.

Here is the code. Or checkout out a working jsfiddle demo

// makeWorker is a little wrapper for generating web workers from strings
function makeWorker(script) {
    var URL = window.URL || window.webkitURL;
    var Blob = window.Blob;
    var Worker = window.Worker;

    if (!URL || !Blob || !Worker || !script) {
        return null;

    var blob = new Blob([script]);
    var worker = new Worker(URL.createObjectURL(blob));
    return worker;
<div id='log'></div>

<script type='text/worker' id='worker-script'>
    self.addEventListener('message', function(e) {
        postMessage(e.data / 2);
</script><script type='text/javascript'>

// Load a worker from a string, and manually initialize the worker
var inlineWorkerText =
    "self.addEventListener('message', function(e) { postMessage(e.data * 2); } ,false);";
var inlineWorker = makeWorker(inlineWorkerText);
inlineWorker.onmessage = function(e) {
    document.getElementById('log').innerHTML += '<br />Inline: ' + e.data;

// Load a worker from a script of type=text/worker, and use the getWorker helper
var scriptTagWorker = makeWorker(

scriptTagWorker.onmessage = function(e) {
        document.getElementById('log').innerHTML += '<br />Script Tag: ' + e.data;




  1. FileReaderSync - Brian Grinstead Says:

    […] also wrote about how to load web workers without a JavaScript file, but this technique works just fine using a normal external […]

  2. Dick Stokkel Says:

    hi brian, does your colorpicker work with gradients as well?

Comments are closed. Please contact me instead.