What is WebWorker?

What is WebWorker?

Preface

Front-end engineers must have had this experience: when a page loads a large number of js files, the user interface may be "frozen" for a short time. This is easy to understand because js is a single-threaded language. Let's go to the extreme point. A while(){} dead loop appears in a js section. At this time, clicking on the DOM element of the page will not trigger an event. In fact, these asynchronous events are queued and will only be executed after the js of the page is rendered (from setTimeout to talk about the JavaScript running mechanism). At this time, the rendering enters an endless loop, so the user interface is "frozen".

In actual development, although there will be no such infinite loop, a large amount of js rendering will still affect the user experience. At this time, we hope that this time-consuming js code can be executed asynchronously. setTimeout is a good method, but H5 provides a better way, Web Worker! The Web Worker specification solves this problem by allowing Javascript to run in the background. There are many ways for browsers to implement the Web Worker specification, such as using threads, background processes, or processes running on other processor cores, etc. The specific implementation details are not that important. What is important is that developers can now run Javascript without worrying about affecting the user experience.

Since Worker is part of the H5 family, IE6 and the like can be left alone. For detailed browser compatibility, please refer to http://caniuse.com/#search=worker

If there is no Worker

Let's look at this piece of code:

  1. <div style= 'width:100px;height:100px;background-color:red' ></div>
  2. <script>
  3. document.querySelector( 'div' ).onclick = function() {
  4. console.log( 'hello world' );
  5. };
  6.  
  7. function fibonacci(n) {
  8. return n < 2 ? n : arguments.callee(n - 1 ) + arguments.callee(n - 2 );
  9. }
  10.  
  11. console.log(fibonacci( 36 ));
  12. </script>

A div is written on the page, and its click event is listened to. In js, the 36th term of the Fibonacci sequence needs to be calculated and output. The user experience of such a page is very poor. If fibonacci is not completed, the click event of the div cannot be responded in time, and recursively solving the Fibonacci sequence terms is quite time-consuming! Such a time-consuming js code is best left to the worker!

The ultimate weapon: Worker

The usage of Worker is very simple.

You can create a new Web Worker by instantiating a Worker object and passing in the name of the JavaScript file to be executed:

  1. var worker = new Worker( 'worker.js' );

This code will cause the browser to download worker.js, but the code in the file will not actually be executed until the Worker receives the message. To pass a message to the Worker, you can use the postMessage() method. For example, if I want to tell the Worker that I need to find the 36th term of the Fibonacci sequence:

  1. worker.postMessage( 36 );

Let's take a look at how Worker receives messages. When the page calls postMessage() on the worker object, the data is passed to the worker asynchronously, triggering the message event in the worker. In order to process the data from the page, an onmessage event handler must also be created. (worker.js code)

  1. self.onmessage = function(event) {
  2. var data = event.data;
  3. console.log(fibonacci(data));
  4. };
  5.  
  6. function fibonacci(n) {
  7. return n < 2 ? n : arguments.callee(n - 1 ) + arguments.callee(n - 2 );
  8. }

The page can pass data to the Worker, and the Worker can also pass data back. The page listens through the message event:

  1. worker.onmessage = function(event) {
  2. var data = event.data;
  3. };

Workers communicate with pages through message and error events. Data from workers is stored in event.data. When a worker cannot complete a given task, an error event is triggered. Specifically, the error event is triggered whenever an error is encountered during the execution of the Javascript inside the worker. When an error event occurs, the event object contains three properties: filename, lineno, and message, which represent the file name, line number, and complete error message of the error respectively:

  1. worker.onerror = function(event) {
  2. console.log(event.filename, event.lineno, event.message);
  3. };

We recommend that you write an error event when using a worker, just like you always need to write a remedial action when the acquisition fails when using ajax.

Complete code:

html file:

  1. <div style= 'width:100px;height:100px;background-color:red' ></div>
  2. <script>
  3. document.querySelector( 'div' ).onclick = function() {
  4. console.log( 'hello world' );
  5. };
  6.  
  7. var worker = new Worker( 'worker.js' );
  8. worker.postMessage( 36 );
  9. worker.onmessage = function(event) {
  10. var data = event.data;
  11. console.log(data)
  12. };
  13.  
  14. worker.onerror = function(event) {
  15. console.log(event.filename, event.lineno, event.message);
  16. };
  17. </script>

worker.js file:

  1. self.onmessage = function(event) {
  2. var data = event.data;
  3. var ans = fibonacci(data);
  4. this .postMessage(ans);
  5. };
  6.  
  7. function fibonacci(n) {
  8. return n < 2 ? n : arguments.callee(n - 1 ) + arguments.callee(n - 2 );
  9. }

Brief summary:

WEB main thread:

  1. Create a worker by loading a js file through var worker = new Worker(url) and return a worker instance.
  2. Send data to the worker through the worker.postMessage(data) method.
  3. Bind the worker.onmessage method to receive the data sent by the worker.
  4. You can use worker.terminate() to terminate the execution of a worker.

Worker new thread:

  1. Bind the onmessage method to receive data sent by the main thread.
  2. Send data to the main thread through the postMessage(data) method.
  3. You can use self.close() to terminate the execution of a worker.

Worker Other

The most important thing to know about Web Workers is that the Javascript code it executes is in a completely different scope, and does not share a scope with the code in the current web page. In Web Workers, there is also a global object (the worker object itself, and this and self refer to the worker object itself) and other objects and methods. The code in Web Workers cannot access the DOM. So what objects can the code in Workers access and what methods does it have?

  1. A minimized navigator object, including onLine, appName, appVersion, userAgent, and platform properties
  2. Read-only location object
  3. setTimeout(), setInterval(), clearTimeout(), clearInterval() methods
  4. XMLHttpRequest Constructor

Worker can be terminated at any time. In worker.js, we can use the self.close() method, and in the page, we can use the worker.terminal() method, then the error and message events will not be triggered.

<<:  Tmall experts are here to teach you! How to systematically learn front-end development from scratch?

>>:  How Chinese programmers get Facebook offers

Recommend

Two types of marketing strategies that are both perfect and ingenious

I read a statement a few days ago that in Go and ...

How to quickly build a marketing and promotion system for B2B products?

In the past two years, the SAAS product market ha...

Tesla's Autopilot is declared not guilty and the new Model S/X 100d is launched

Ever since foreign media revealed that an America...

QQ advertising traffic diversion and delivery strategy!

When talking about Tencent Advertising , what APP...

Fish's memory is only seven seconds? Fish: You underestimate me!

The concept of "fish only have a memory of s...

Detailed illustration of the review process for Google Analytics and Google Ads!

Google Ads is an important platform for online me...

Sand onion, a vegetable blind spot for southerners

If you were asked to quickly list the ingredients...