我们真的需要多线程 JavaScript 吗?
我最近听说了 Web Workers 规范,它定义了多线程 JavaScript 的 API。但是在使用客户端脚本(以及事件驱动范例)这么长时间之后,我真的没有看到使用多线程的意义。
我可以看到 JavaScript 引擎和浏览器渲染引擎如何从多线程中受益,但我确实没有看到将这种能力交给应用程序程序员有多大好处。
I have recently heard about the Web Workers spec that defines API for multi-threading JavaScript. But after working with client side scripting for so long now (and event-driven paradigm), I don't really see a point with using multiple thread.
I can see how the JavaScript engine and browser rendering engine can benefit from multi-threading, but I really don't see much benefit in handing this power to application programmers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
维基百科的文章实际上很好地回答了你的问题。
我们开发人员拥有这样的权力,这样我们就可以专门将那些会对用户造成干扰的任务转移给网络工作者。浏览器不知道您的自定义界面正常运行需要哪些脚本,但您知道。
如果您有一个脚本会阻止页面渲染 10 秒,但对于网站运行来说并不是必需的,您可以将其卸载给网络工作人员。这样做可以让用户与页面交互,而不是强迫他们等待 10 秒才能执行该脚本。在某种程度上,它就像AJAX一样,可以在界面加载后注入东西,这样就不会延迟用户的交互。
The Wikipedia article actually answers your question fairly well.
The power is given to us developers so that we can specifically offload tasks that would be disruptive to users to a web worker. The browser does not know which scripts are necessary for your custom interface to function properly, but you do.
If you've got a script that blocks the page rendering for 10 seconds but isn't necessary for the website to function, you could offload it to a web worker. Doing so allows your users to interact with the page instead of forcing them to wait 10 seconds for that script to execute. In a way, it's like AJAX in that things can be injected in after the interface loads so as to not delay users' interaction.