Home > Web Front-end > H5 Tutorial > body text

HTML5 new features Web Worker

黄舟
Release: 2017-03-30 11:54:06
Original
1310 people have browsed it

1. Overview

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:

    Same domain restriction: The script file loaded by the sub-thread must be in the same domain as the script file of the main thread.
  • ##DOM restriction: The sub-thread cannot read the DOM object of the restricted web page. That is, the document, window, and parent objects cannot be obtained by the child thread. (However, the navigator object and the location object can be obtained.)
  • Script limitation: The child thread cannot read the global page of the web page. Variables and functions cannot execute the alert and confirm methods, but they can execute setInterval and setTimeout, and use the XMLHttpRequest object to make AJAX requests
  • File restrictions: child threads cannot read local files. That is, the child thread cannot open the local file system (file://), and the script it loads must come from the network.
  • ## 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 {    // 不支持}
    Copy after login
  • 2. Create and start child threads

. Within the main thread, use the

new

command to call the Worker method to create a new sub-thread. The parameter of the

var worker = new Worker('work.js');
Copy after login

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');
Copy after login

The parameter of the postMessage method is the signal passed by the main thread to the child thread. It can be either a

string

or an object.

worker.postMessage({method: 'each', args: ['work']});
Copy after login

3. Sub-thread's EventMonitoring

In the sub-thread, there must be a callback function to monitor the message event.

//File: work.jsself.addEventListener('message', function(e) {

    self.postMessage('You said: ' + e.data);

}, false);
Copy after login

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.

4. Event monitoring of the main thread

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);
Copy after login

5,

Error handling

The main thread can monitor whether an error occurs in the child thread. If an error occurs, the error event of the main thread will be triggered.
worker.onerror(function(e) {
    console.log(e);
});// orworker.addEventListener('error', function(e) {
    console.log(e);
}, false);
Copy after login
6. Close the child thread

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();
Copy after login

You can also close yourself internally in the child thread.

self.close();
Copy after login

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 value

instead of the address. Modifications of the communication content by the sub-thread will not affect the main thread. In fact, the internal operating mechanism of the browser is to serialize the communication content first, and then send the serialized string to the child thread, which then restores it.

The 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]);
Copy after login

8、同页面的Web Worker

通常情况下,子线程载入的是一个单独的JavaScript文件,但是也可以载入与主线程在同一个网页的代码。假设网页代码如下:

<!DOCTYPE html>
    <body>
        <script id="worker" type="app/worker">

            addEventListener(&#39;message&#39;, function() {
                postMessage(&#39;Im reading Tech.pro&#39;);
            }, false);        </script>
    </body></html>
Copy after login

我们可以读取页面的script,用worker来处理。

var blob = new Blob([document.querySelector(&#39;#workere&#39;).textContent]);
Copy after login

这里需要把代码当作二进制数据读取,所以使用Blob接口。然后,这个二进制对象转为URL,再通过这个URL创建worker。

var url = window.URL.createObjectURL(blob);var worker = new Worker(url);
Copy after login

部署事件监听代码。

worker.addEventListener(&#39;message&#39;, function(e) {
    console.log(e.data);
}, false);
Copy after login

最后启动worker。

worker.postMessage(&#39;&#39;);
Copy after login

整个页面的代码如下:


    
        

        <script>
            (function() {                
            var blob = new Blob([document.querySelector(&#39;#worker&#39;).textContent]);                
            var url = window.URL.createObjectURL(blob);                
            var worker = new Worker(url);

                worker.addEventListener(&#39;message&#39;, function(e) {
                    console.log(e.data);
                }, false);

                worker.postMessage(&amp;#39;&amp;#39;);
            })();        </script>
    
Copy after login

可以看到,主线程和子线程的代码都在同一个网页上面。

上面所讲的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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!