Skip to content

Instantly share code, notes, and snippets.

Created June 24, 2013 12:21
  • Star 52 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Create web workers without a separate worker JS files. Source:
function worker() {
setInterval(function() {
postMessage({foo: "bar"});
}, 1000);
var code = worker.toString();
code = code.substring(code.indexOf("{")+1, code.lastIndexOf("}"));
var blob = new Blob([code], {type: "application/javascript"});
var worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = function(m) {
console.log("msg", m);
Copy link

Very kewel.

Copy link

Super helpful! 👍

Copy link

helpful a lot on right time! Thx!

Copy link

clarkdo commented Jan 14, 2017

looks very good

Copy link

Thank you for this example. Little mistake: worker function and worker object names intersection.

In addition for this.
If you use webworkers for short tasks, you should release them by calling close(), see example here
Otherwise you will get a thread leak.

Copy link

segg21 commented Jul 2, 2017

@AlekseyPi lol actually he's conserving memory. That worker function wasn't needed, as it was converted to a blob. It was no longer needed. No need to create extra variables.

Also, GC cleans up Workers, but yes, recommended to close that aswell.

Copy link

segg21 commented Jul 2, 2017

and NOT just for shorter (Tasks), but for all.

Copy link


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