Last active
December 17, 2015 08:09
-
-
Save yyx990803/5578034 to your computer and use it in GitHub Desktop.
Turn a function's body into a worker.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This also comes handy when trying to pack a worker script into a Browserify bundle: