识别 JS 脚本何时作为 Worker 运行
我有一个脚本,可以直接运行,也可以在浏览器中作为 Web Worker 运行。我想仅在作为工作人员运行时运行此脚本的一部分;所以我的问题是,脚本如何将自己标识为以这种方式运行?
我在规范中看不到任何允许这种情况发生的内容;我错过了一些明显的东西吗?
I have a script which can be run either directly or, when available in the browser, as a Web Worker. I'd like to run a portion of this script only when run as a worker; so my question is, how can a script identify itself as being run this way?
I can't see anything in the spec that would allow this to happen; am I missing something obvious?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
下面:
worker.js 作为脚本和工作线程被调用。
worker.js 包含:
在工作环境中,postMessage 成功,在脚本环境中失败,因为它未定义,或者在浏览器中需要第二个参数。
输出是:
chrome :
firefox :
opera:
All under Ubuntu。
In the following :
worker.js is invoked both as a script and as a worker.
worker.js contains :
In the worker environment, the postMessage succeeds, in the script environment it fails because either it is undefined or, in a browser, it requires a second argument.
Output is :
chrome :
firefox :
opera:
All under Ubuntu.
我会使用 Modernizr (它是一个开源 JavaScript 库,可以帮助您避免一次又一次地重新发明轮子)。
I would use Modernizr (it is an open-source JavaScript library that helps you NOT to reinventing the wheel again and again).