Reliably Detect If The Script Is Executing In A Web Worker
I am currently writing a little library in JavaScript to help me delegate to a web-worker some heavy computation . For some reasons (mainly for the ability to debug in the UI threa
Solution 1:
Quite late to the game on this one, but here's the best, most bulletproofy way I could come up with:
// run this in global scope of window or worker. since window.self = window, we're ok
if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
// huzzah! a worker!
} else {
// I'm a window... sad trombone.
}
Solution 2:
Emscripten does:
// *** Environment setup code ***
var ENVIRONMENT_IS_NODE = typeof process === 'object' && typeof require === 'function';
var ENVIRONMENT_IS_WEB = typeof window === 'object';
var ENVIRONMENT_IS_WORKER = typeof importScripts === 'function';
var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
Solution 3:
As noted there is an answer in another thread which says to check for the presence of a document object on the window. I wanted to however make a modification to your code to avoid doing a try/catch block which slows execution of JS in Chrome and likely in other browsers as well.
EDIT: I made an error previously in assuming there was a window object in the global scope. I usually add
//This is likely SharedWorkerContext or DedicatedWorkerContext
window=this;
to the top of my worker loader script this allows all functions that use window feature detection to not blow up. Then you may use the function below.
function testEnv() {
if (window.document === undefined) {
postMessage("I'm fairly confident I'm a webworker");
} else {
console.log("I'm fairly confident I'm in the renderer thread");
}
}
Alternatively without the window assignment as long as its at top level scope.
var self = this;
function() {
if(self.document === undefined) {
postMessage("I'm fairly confident I'm a webworker");
} else {
console.log("I'm fairly confident I'm in the renderer thread");
}
}
Post a Comment for "Reliably Detect If The Script Is Executing In A Web Worker"