识别JS脚本何时作为Worker运行

Identifying when a JS script is running as a Worker

本文关键字:Worker 运行 何时作 JS 脚本 识别      更新时间:2023-09-26

我有一个脚本,可以直接运行,或者在浏览器中可用时,作为Web Worker。我想只在作为工人运行时运行这个脚本的一部分;所以我的问题是,一个脚本如何识别自己正在以这种方式运行?

我在规范中看不到任何允许这种情况发生的东西;我错过了什么明显的东西吗?

在下面:

<html>
<head>
<title>Worker</title>
</head>
<body>
</body>
<script >
  var w = new Worker ('worker.js');
  w.onmessage = function (e) {
    document.body.innerHTML += '<br>' + 'WORKER : ' + e.data;
  };
</script>
<script src='worker.js'></script>
</html>

worker.js作为脚本和worker调用。

worker.js包含:

  var msg = 'postMessage is ' + postMessage.toString () + 
          ', self.constructor is ' + self.constructor;
  try {
    postMessage (msg);
  } catch (e) {
    document.body.innerHTML += '<br>SCRIPT : ' + msg;
  }  

在工作环境中,postMessage成功;在脚本环境中,它失败,因为它没有定义,或者在浏览器中,它需要第二个参数。

输出为:

chrome:

SCRIPT : postMessage is function () { [native code] }, self.constructor is function DOMWindow() { [native code] } 
WORKER : postMessage is function postMessage() { [native code] }, self.constructor is function DedicatedWorkerContext() { [native code] }
firefox:

SCRIPT : postMessage is function postMessage() { [native code] }, self.constructor is [object Window]
WORKER : postMessage is function postMessage() { [native code] }, self.constructor is function DedicatedWorkerGlobalScope() { [native code] }
歌剧

:

WORKER : postMessage is function postMessage() { [native code] }, self.constructor is function Object() { [native code] }
SCRIPT : postMessage is function postMessage() { [native code] }, self.constructor is function Object() { [native code] }

我会使用Modernizr(它是一个开源的JavaScript库,可以帮助您避免一次又一次地重新发明轮子)。

if (Modernizr.webworkers) {
  // window.Worker is available!
} 
else {
  // no native support for web workers
}