问题
This question already has an answer here:
- Any standard mechanism for detecting if a JavaScript is executing as a WebWorker? 5 answers
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 thread and then run the same code in a worker) I'd like to detect if the script is currently running in a worker or in the UI thread.
I'm not a seasoned JavaScript developper and I would like to ensure that the following function will reliably detect if I'm in a worker or not :
function testenv() {
try{
if (importScripts) {
postMessage("I think I'm in a worker actually.");
}
} catch (e) {
if (e instanceof ReferenceError) {
console.log("I'm the UI thread.");
} else {
throw e;
}
}
}
So, does it ?
回答1:
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");
}
}
回答2:
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.
}
回答3:
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;
(Emscripten on Github)
来源:https://stackoverflow.com/questions/7931182/reliably-detect-if-the-script-is-executing-in-a-web-worker