JavaScript language uses a single thread Model, that is to say, all tasks are arranged in a queue, and only one thing can be done at a time. As the computing power of computers increases, this brings great inconvenience. It is even more so when Long Qi considers that File API allows JavaScript to read local files. It is to create a multi-threaded environment for JavaScript, allowing the main thread to assign some tasks to sub-threads. While the main thread is running, the sub-threads run in the background, and the two do not interfere with each other until the sub-thread completes the calculation task and then returns the results. Main thread. Therefore, each sub-thread is like a "worker", completing its work silently.
Web Worker has the following characteristics:
## Before using, check whether the browser supports this API. Supported browsers include IE 10+, Firefox 3.6+, Safari 4.0+, Chrome and Opera 11, but mobile browsers do not yet support
if (window.Worker) { // 支持} else { // 不支持}
. Within the main thread, use the
newvar worker = new Worker('work.js');
Worker method is a script file, which is the task to be completed by the sub-thread. The code above is work.js. Since the child thread cannot read the local file system, the script file must come from the network. If the download is unsuccessful, such as a 404 error, the child thread will fail silently. After the sub-thread is created, it is not started. It must wait for the main thread to call the postMessage method, that is, it will not start until a signal is sent.
worker.postMessage('hello world');
The parameter of the postMessage method is the signal passed by the main thread to the child thread. It can be either a
stringor an object.
worker.postMessage({method: 'each', args: ['work']});
3. Sub-thread's EventMonitoring
//File: work.jsself.addEventListener('message', function(e) { self.postMessage('You said: ' + e.data); }, false);
self represents the sub-thread itself, and self.addEventListener represents the designated callback function for the message event of the sub-thread (you can also directly specify the value of the onmessage attribute). The parameter
of the callback function is an event object, and its data attribute contains the signal sent by the main thread. self.postMessage means that the child thread sends a signal to the main thread. According to different signal values sent by the main thread, the sub-thread can call different methods. 'message', method = args = reply =);
The main thread must also specify the callback function of the message event to listen for signals sent by the child thread.
// File: main.jsworker.addEventListener('message', function(e) { console.log(e.data); }, false);
worker.onerror(function(e) { console.log(e); });// orworker.addEventListener('error', function(e) { console.log(e); }, false);
After use, in order to save system resources, we must call the terminate method on the main thread to manually close the child thread.
worker.terminate();
self.close();
7. Data communication between the main thread and the sub-thread
The communication content between the main thread and the sub-thread can be text or an object. It should be noted that this kind of communication is a copy relationship, that is,
passes the valueThe main thread and the sub-thread can also exchange binary data, such as File, Blob, ArrayBuffer and other objects, and can also be sent between threads.
但是,用拷贝方式发送二进制数据,会造成性能问题。比如,主线程向子线程发送一个500MB文件,默认情况下浏览器会生成一个原文件的拷贝。为了解决这个问题,JavaScript允许主线程把二进制数据直接转移给子线程,但是一旦转移,主线程就无法再使用这些二进制数据了,这是为了防止出现多个线程同时修改数据的麻烦局面。这种转移数据的方法,叫做Transferable Objects。
如果要使用该方法,postMessage方法的最后一个参数必须是一个数组,用来指定前面发送的哪些值可以被转移给子线程。
worker.postMessage(arrayBuffer, [arrayBuffer]);
通常情况下,子线程载入的是一个单独的JavaScript文件,但是也可以载入与主线程在同一个网页的代码。假设网页代码如下:
<!DOCTYPE html> <body> <script id="worker" type="app/worker"> addEventListener('message', function() { postMessage('Im reading Tech.pro'); }, false); </script> </body></html>
我们可以读取页面的script,用worker来处理。
var blob = new Blob([document.querySelector('#workere').textContent]);
这里需要把代码当作二进制数据读取,所以使用Blob接口。然后,这个二进制对象转为URL,再通过这个URL创建worker。
var url = window.URL.createObjectURL(blob);var worker = new Worker(url);
部署事件监听代码。
worker.addEventListener('message', function(e) { console.log(e.data); }, false);
最后启动worker。
worker.postMessage('');
整个页面的代码如下:
<script> (function() { var blob = new Blob([document.querySelector('#worker').textContent]); var url = window.URL.createObjectURL(blob); var worker = new Worker(url); worker.addEventListener('message', function(e) { console.log(e.data); }, false); worker.postMessage(&#39;&#39;); })(); </script>
可以看到,主线程和子线程的代码都在同一个网页上面。
上面所讲的Web Worker都是专属于某个网页的,当该网页关闭,worker就自动结束。除此之外,还有一种共享式的Web Worker,允许多个浏览器窗口共享同一个worker,只有当所有窗口关闭,它才会结束。这种共享式的Worker用SharedWorker对象来创建,因为适用场合不多,这里就省略了。
The above is the detailed content of HTML5 new features Web Worker. For more information, please follow other related articles on the PHP Chinese website!