可靠地检测脚本是否在Web worker中执行 [英] Reliably detect if the script is executing in a web worker
问题描述
我目前正在用JavaScript编写一个小库来帮助我委托一个网络工作者进行一些繁重的计算。
I am currently writing a little library in JavaScript to help me delegate to a web-worker some heavy computation .
出于某些原因(主要是因为调试能力)在UI线程中然后在worker中运行相同的代码)我想检测脚本当前是在worker还是在UI线程中运行。
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.
我不是一个经验丰富的JavaScript开发人员,我想确保以下函数能够可靠地检测我是否在工作中:
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;
}
}
}
那么,是吗? / p>
So, does it ?
推荐答案
如上所述,答案在,它说要检查窗口上是否存在文档对象。我想对您的代码进行修改以避免执行try / catch块,也可能在其他浏览器中减慢。
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.
编辑:之前我假设有一个错误全局范围内的窗口对象。我通常添加
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");
}
}
这篇关于可靠地检测脚本是否在Web worker中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!