Last active
October 13, 2015 10:08
-
-
Save jaubourg/4180176 to your computer and use it in GitHub Desktop.
Create a Web Worker from a function, not a file
This file contains hidden or 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
// Web Workers can be built from data URLs! | |
// See http://www.whatwg.org/specs/web-apps/current-work/multipage/workers.html#dom-worker | |
// Chrome doesn't seem to support this yet but FF does | |
// So how about a helper to create a Web Worker from a function | |
var InlineWorker = (function() { | |
var r_func = /^\s*function\s*\(.*?\)\s*\{|\}\s*$/g; | |
return function( func, encoding ) { | |
return new Worker( | |
"data:application/javascript;charset=" + | |
( encoding || "UTF-8" ) + "," + | |
encodeURIComponent( func.toString().replace(r_func,"") ) | |
); | |
}; | |
})(); | |
// Then, in your app | |
var worker = InlineWorker(function( self /* argument is optional */ ) { | |
self.addEventListener( "message", function(e) { | |
self.postMessage( "I received: " + e.data ); | |
}, false ); | |
}); | |
worker.addEventListener( "message", function( e ) { | |
console.log( "Worker said: ", e.data ); | |
}, false ); | |
worker.postMessage( "Hello World" ); // Will output "I received: Hello World". | |
// Beware: the function body is "serialized", so scope is lost!!! | |
var inScope = "I am in the original scope"; | |
InlineWorker(function( self /* argument is optional */ ) { | |
inScope; // throws an exception | |
}); |
Look who didn't see the comment before? \o/
The r_func is here in case you give a named function:
function fn() {}
InlineWorker( fn );
I just don't want fn
defined within the worker... call me pedantic ;)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Instead of removing the function with
r_func
you could've simply wrapped the thing in'(' + func.toString() + ')()'
.