Browser-side JavaScript executes in a single-threaded manner, meaning that JavaScript and UI rendering occupy the same main thread, which means that if JavaScript does heavy data processing, UI rendering is likely to be blocked and the browser will stagnate, degrading the user experience.

To do this, JavaScript provides asynchronous operations such as timer (setTimeout, setInterval) events, Ajax requests, I/O callbacks, and so on. High-load tasks can be processed asynchronously, and they will be placed in the browser’s Event loop, which will be executed on a first-in-first-out basis when the JavaScript runtime thread is idle.

Nodejs prides itself on asynchronous processing

Through similar timer, the callback function such as asynchronous programming way is enough in the usual work, but if do complicated calculation, the shortcomings of this approach is reflected gradually, such as settimeout to value is not correct, or pages with complex operation is very easy to trigger suspended animation, asynchronous code affects the code execution of the main thread, Asynchrony, after all, is a single thread and cannot fundamentally solve the problem.

The Web Worker is part of the HTML5 standard. This specification defines a set of apis that allow a JavaScript program to run in another thread than the main thread. Assign some tasks to the latter to run. While the main thread is running, the Worker (child) thread is running in the background without interfering with each other. Wait until the Worker thread completes the calculation and returns the result to the main thread. The advantage of this is that when computationally intensive or high-latency tasks are taken on by Worker threads, the main thread (usually responsible for UI interactions) will flow smoothly and will not be blocked or slowed down.

What is a Web worker

Worker is a method on the Window object that can check whether your browser supports workers in the following ways

If (window. The Worker) {... Your code... }Copy the code

A worker is an object created using a constructor (worker ()) that requires passing in a JavaScript file containing the code to be run in the worker thread. Something like this:

let myWorker = new Worker('worker.js');
Copy the code

The worker communicates data with the onMessage event via the postMessage() method. The main thread and child threads are bidirectional and can both send and listen for events. Sending a message to a worker requires doing this (main.js) :

myWorker.postMessage('hello, world'); Onmessage = function (event) {console.log('Received message '+ event.data); doSomething(); }Copy the code

All data sent by postMessage is copied (except for ArrayBuffer types), and the child thread of data is similarly passed (worker.js).

addEventListener('message', function (e) {
	postMessage('You said: ' + e.data);
}, false);
Copy the code

To save system resources, you can manually stop the subthread after it finishes running. If the worker is not listening for messages, it will automatically shut down when all tasks (including counters) are finished.

// Close worker.terminate(); // Thread close() in child thread; Worker.addeventlistener ('error', function (e) {console.log(' error', e); });Copy the code

The Web worker itself is simple, but it is extremely restrictive.

Two, the problem of use

1. Origin restriction The script file (worker.js) assigned to the Worker thread must be of the same origin as the script file (main.js) of the main thread. The same-origin restrictions include protocols, domain names, and ports, and do not support local addresses (file://). The worker.js domain name of the main thread refers to the domain where the HTML file resides. The URL loaded through new worker (URL) belongs to the domain of CDN, which will cause cross-domain problems. In real development, we don’t put all the code in a file and let the child threads load it, we definitely choose modular development. Combine code into a file using a tool or library, and then generate a file URL from the child thread’s code. Solution: (1) Convert dynamically generated scripts into Blob objects. (2) Then create a URL for the Blob object. (3) Finally, pass the created URL as the address to the Worker’s constructor.

let script = 'console.log("hello world!" ); ' let workerBlob = new Blob([script], { type: "text/javascript" }); let url = URL.createObjectURL(workerBlob); let worker = new Worker(url);Copy the code

2. Access restriction The global object where the Worker child thread is located is not in the same context as the main thread, so the DOM object of the page where the main thread is located cannot be read, nor can the document, window, parent objects be used. The direction of the global object is changed. The window needs to be rewritten as self. It cannot execute methods such as alert() and Confirm () and can only read part of the data in the Navigator object. In addition, Chrome console.log() is available and also supports debugger breakpoints, increasing debugging convenience. The child thread can use XMLHttpRequest object to make AJAX requests, setTimeout() setInterval() method, or use websocket for continuous links. It is also possible to load additional script files through importScripts(URL), but still not across domains.

Three, application scenarios

The original intention of Web Worke design is to do time-consuming computation tasks and big data processing. Such computation in worker will not interrupt the operation of foreground users and avoid unnecessary user experience caused by code lag. For example, deal with large amounts of data returned by Ajax, read files uploaded by users, calculate MD5, change the filter of canvas bitmap, analyze video and audio files, etc. In addition to the lack of DOM and BOM operation ability, worker also has very powerful JS logical operation and processing ability, which is equivalent to nodeJS running environment.

2. High-frequency user interaction High-frequency user interaction is suitable for assisting users to complete input error correction and correction functions based on their input habits, historical records, cache and other information. Response processing frequently input by users can also be considered to be executed in Web workers. For example, we could make an application like Word that looks up the dictionary in the background while the user is typing, helps the user automatically correct errors, and so on.

3, data prefetching For some products to Taiwan before and after interaction with a large number of data, you can open a new thread is dedicated to data prefetching and buffer data, write and change the local web database, run continued for a long time, will not be on the main thread of activities (such as user, click on the button, submit the form), but also to respond to the main thread communication at any time. It can also be used with XMLHttpRequest and WebSocket for continuous communication to achieve the guard process.

Iv. Compatibility

Generally speaking, the compatibility is good, mobile terminal can be trusted to use, desktop terminal requirements are not high, can also use.

Five, the summary

As for the new technology of Web worker, Tencent News front-end group has been widely used no matter in PC or mobile Web. The implementation of Web Worker brings background computing ability to front-end programs and can realize the separation of main UI thread and complex counting thread. Thus, it greatly reduces the interface rendering jam and frame drop caused by the large amount of calculation, and makes greater use of the performance of the terminal hardware. SuperWorker can solve the problems of event binding and same origin policy. The biggest problem with superWorker is that it is not compatible with IE9. In places where compatibility requirements are not so strict, use it as much as possible.


IVWEB Technology Weekly shocked online, pay attention to the public number: IVWEB community, weekly timing push quality articles.

  • Collection of weekly articles: weekly
  • Team open source project: Feflow