确定JS脚本何时作为Worker运行

时间:2011-12-15 16:14:10

标签: javascript html5 web-worker

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

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

2 个答案:

答案 0 :(得分: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;
  }  

在worker环境中,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] }

所有在Ubuntu下。

答案 1 :(得分:0)

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

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