且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-04 22:16:04

如上所述,答案在,它说要检查窗口上是否存在文档对象。我想对您的代码进行修改以避免执行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");
  }
}