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);
    },false);
</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(
    document.getElementById('worker-script').textContent
);

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

inlineWorker.postMessage(1);
inlineWorker.postMessage(2);
inlineWorker.postMessage(100);
scriptTagWorker.postMessage(1);
scriptTagWorker.postMessage(2);
scriptTagWorker.postMessage(100);

</script>

Comments

  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.