2011-12-15 64 views
3

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

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

+1

您可以检查是否存在某个属性;我相信`window`没有在worker脚本中定义(即`typeof window ===“undefined”?worker:normal`)。虽然我不完全确定。 – pimvdb 2011-12-15 16:16:01

+0

我希望避免这样做 - 因为窗口在其他环境中不可用 - 但我可能必须! – Graham 2011-12-15 23:41:03

回答

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.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下。

0

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

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