3

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

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

4

2 回答 2

1

在下面的 :

<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 成功,在脚本环境中失败,因为它要么未定义,要么在浏览器中需要第二个参数。

输出是:

铬合金 :

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] }

火狐:

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] }

全部在 Ubuntu 下。

于 2011-12-25T18:44:42.147 回答
0

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

if (Modernizr.webworkers) {
  // window.Worker is available!
} 
else {
  // no native support for web workers
}
于 2011-12-25T09:24:12.770 回答