Anyway, in JS libraries especially, it can be useful to spawn worker threads, but it's inconvenient to have those functions in entirely separate files sometimes. I'm not 100% sure of the implications yet, but I had some success with the following template:
Template for worker script in same file as main script;
adapted from http://stackoverflow.com/a/10136565/1048862
to make it a little cleaner
var isWorker = !global.document;
// Entry point for when we're a worker thread
global.onmessage = messageReceived;
// Worker thread execution goes here...
// This is how to pass messages back to the main/parent script
// global.postMessage("From worker!");
// (messages can also be objects)
console.log("Worker received message from parent:");
// Entry point for the main thread
var SCRIPT_PATH = getScriptPath();
// Main script execution goes here...
// This is how to start new workers and pass messages:
// var w = newWorker();
// w.postMessage("From parent!");
var id = "worker" + String(Math.random()).substr(2);
var w = new global.Worker(SCRIPT_PATH);
w.onmessage = messageReceived;
console.log("Parent received message from worker: ", e.data);
Anyway, I think I might use this again.