Skip to content

Instantly share code, notes, and snippets.

@yyx990803
Last active December 17, 2015 08:09
Show Gist options
  • Save yyx990803/5578034 to your computer and use it in GitHub Desktop.
Save yyx990803/5578034 to your computer and use it in GitHub Desktop.
Turn a function's body into a worker.
// Turns a function's body into a worker
var workerify = function (func) {
if (typeof func !== 'function') {
throw new Error('expects a function to workerify.')
}
var script = func.toString().match(/^function[^{]*{((.|\n)*)}$/)[1],
blob = new Blob([script], {'type': 'application/javascript'}),
url = window.URL.createObjectURL(blob)
return new Worker(url)
}
// Usage Example:
var worker = workerify(function () {
// just write code as if you are inside a worker
// note: you don't have access to anything outside of this function
self.onmessage = function (e) {
self.postMessage('pong')
}
})
worker.onmessage = function (e) {
console.log(e.data)
}
worker.postMessage('ping') // pong
@yyx990803
Copy link
Author

This also comes handy when trying to pack a worker script into a Browserify bundle:

// main.js
var worker = workerify(require('./worker-script'))
// worker-script.js
module.exports = function () {
    // do work
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment