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

发布于 2024-12-12 18:39:10 字数 531 浏览 2 评论 0原文

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

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

我不是经验丰富的 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;
        }
    }
}

那么,是吗?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

遥远的她 2024-12-19 18:39:10

虽然这个游戏已经很晚了,但这是我能想到的最好、最可靠的方法:

// 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 not a worker... sad trombone.
}

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 not a worker... sad trombone.
}
听闻余生 2024-12-19 18:39:10

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;

Github 上的 Emscripten

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)

等待我真够勒 2024-12-19 18:39:10

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

编辑:我之前在假设全局范围内有一个窗口对象时犯了一个错误。我通常添加

//This is likely SharedWorkerContext or DedicatedWorkerContext
window=this;

到我的工作加载程序脚本的顶部,这允许所有使用窗口功能检测的函数不会崩溃。那么你就可以使用下面的功能了。

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

或者,只要其在顶级范围内,就无需窗口分配。

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

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");
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文