Skip to content

Instantly share code, notes, and snippets.

@psiphi75
Last active February 28, 2017 08:52
Show Gist options
  • Save psiphi75/41df47457c5f2869440c813933e2c4f9 to your computer and use it in GitHub Desktop.
Save psiphi75/41df47457c5f2869440c813933e2c4f9 to your computer and use it in GitHub Desktop.
Implementing workerjs in code that is used both in the browser and in Node.js
// A reliable method to detect if we are running in Node.js
const isNodeJS = new Function('try {return this===global;}catch(e){return false;}')();
var UniversalWorker;
var uri;
if (isNodeJS) {
// Dynamically load "workerjs"
UniversalWorker = require('workerjs');
// The actual worker code is the same for Node.js, but the
// location is different because we use browserify.
uri = 'src/RayTraceWorker.js';
} else {
// If we are in the browser, "Worker" is already defined.
UniversalWorker = Worker;
uri = 'www/RayTraceWorker.js';
}
var worker = new UniversalWorker(uri);
// ... continue to use the worker.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment