可靠地检测脚本是否在 Web Worker 中执行
我目前正在用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
虽然这个游戏已经很晚了,但这是我能想到的最好、最可靠的方法:
Quite late to the game on this one, but here's the best, most bulletproofy way I could come up with:
Emscripten 的作用是:(
Github 上的 Emscripten)
Emscripten does:
(Emscripten on Github)
如前所述,另一个线程,它表示要检查窗口上是否存在文档对象。然而,我想对您的代码进行修改,以避免执行 try/catch 块 会减慢 Chrome 中 JS 的执行速度,在其他浏览器中也可能如此。
编辑:我之前在假设全局范围内有一个窗口对象时犯了一个错误。我通常添加
到我的工作加载程序脚本的顶部,这允许所有使用窗口功能检测的函数不会崩溃。那么你就可以使用下面的功能了。
或者,只要其在顶级范围内,就无需窗口分配。
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
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.
Alternatively without the window assignment as long as its at top level scope.