3

直接実行できるスクリプト、またはブラウザーで使用可能な場合はWebワーカーとして実行できるスクリプトがあります。このスクリプトの一部は、ワーカーとして実行する場合にのみ実行したいと思います。だから私の質問は、スクリプトがこのように実行されていることをどのように識別できるかということです。

これを可能にする仕様には何も表示されません。明らかな何かが欠けていますか?

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.jsに含まれるもの:

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

ワーカー環境ではpostMessageは成功しますが、スクリプト環境では未定義であるか、ブラウザーでは2番目の引数が必要なため失敗します。

出力は:

クローム:

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の下にあります。

于 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 に答える