识别JS脚本何时作为Worker运行
Identifying when a JS script is running as a Worker
我有一个脚本,可以直接运行,或者在浏览器中可用时,作为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
}
相关文章:
- 如何使用phaser使html5游戏在移动设备浏览器上运行
- 使用压缩的JavaScript文件(不是运行时压缩)
- Javascript运行php文件,然后下载文件
- chrome扩展:尽管运行了at:documentidle,js脚本还是过早启动
- 我已经创建了一个jquery转盘,并使用if条件来运行和停止转盘
- Angularjs代码未在匿名函数中运行
- jquery设置为使用参数运行
- 如何根据时间运行不同的脚本
- 当我尝试运行mocha测试时,没有定义Worker
- 当浏览器关闭时,运行Web Worker会发生什么情况
- JavaScript 函数可以检查它是否在 Web Worker 线程上运行吗?
- 加载远程Service Worker,以便在其他域中运行
- 在Tizen web应用程序中,我可以使用javascript web worker在封闭的应用程序上运行后台代码吗?
- 识别JS脚本何时作为Worker运行
- Chrome v54中的Web worker在非活动选项卡中运行时速度慢两倍
- 在knockoutjs-vewmodel的后台运行的Worker
- 是一个Web Worker比运行脚本更快
- 在web worker仍在运行时向其发送消息
- service worker是否会在浏览器关闭的情况下在后台运行?
- Worker可以在Firefox和旧版本的Chrome上运行,但不能在最新版本的Chrome上运行