javascript 可靠地检测脚本是否在 Web Worker 中执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7931182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:46:00  来源:igfitidea点击:

Reliably detect if the script is executing in a web worker

javascriptweb-worker

提问by thomas

I am currently writing a little library in JavaScript to help me delegate to a web-worker some heavy computation .

我目前正在用 JavaScript 编写一个小库,以帮助我将一些繁重的计算委托给网络工作者。

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.

由于某些原因(主要是为了能够在 UI 线程中进行调试,然后在工作线程中运行相同的代码),我想检测脚本当前是在工作线程中还是在 UI 线程中运行。

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 :

我不是经验丰富的 JavaScript 开发人员,我想确保以下函数能够可靠地检测到我是否在工作人员中:

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 ?

那么,是吗?

采纳答案by Channing

As noted there is an answer in another threadwhich 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 Chromeand likely in other browsers as well.

如前所述,另一个线程中有一个答案,它说要检查窗口上是否存在文档对象。然而,我想对您的代码进行修改,以避免执行 try/catch 块,这会减慢 Chrome 中 JS 的执行速度,并且可能在其他浏览器中也是如此。

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");
  }
}

回答by borbulon

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.
}

回答by skalee

Emscripten does:

Emscripten 执行以下操作:

// *** 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)

在 Github 上的 Emscripten