可靠地检测脚本是否在web worker中执行[duplicate]

时间:2023-01-03 19:32:57

This question already has an answer here:

这个问题已经有了答案:

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线程中调试,然后在worker中运行相同的代码),我希望检测该脚本当前是在worker中运行还是在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 ?

所以,不是吗?

3 个解决方案

#1


8  

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.

如前所述,在另一个线程中有一个答案,它要求检查窗口中是否存在文档对象。但是,我想对您的代码进行修改,以避免执行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.

在我的worker加载程序脚本的顶部,这允许所有使用窗口特性检测的函数不崩溃。然后您可以使用下面的函数。

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


24  

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


9  

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)

#1


8  

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.

如前所述,在另一个线程中有一个答案,它要求检查窗口中是否存在文档对象。但是,我想对您的代码进行修改,以避免执行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.

在我的worker加载程序脚本的顶部,这允许所有使用窗口特性检测的函数不崩溃。然后您可以使用下面的函数。

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


24  

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


9  

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)