Browser-side JavaScript is executed in a single-threaded manner, which means that JavaScript and UI rendering occupy the same main thread. That means that if JavaScript performs high-load data processing, UI rendering is likely to be blocked, and the browser will experience lag, which reduces the user experience.
For this reason, JavaScript provides asynchronous operations, such as timer (setTimeout, setInterval) events, Ajax requests, I/O callbacks, and so on. We can use asynchronous processing of high-load tasks, they will be put into the browser’s event task queue (event loop) to go, until the JavaScript runtime execution thread idle, the event queue will be in accordance with the principle of first-in-first-out is executed one by one.
Asynchronous processing that nodejs prides itself on
Through similar timers, callback functions and other asynchronous programming methods in the usual work has been sufficient, but if you do complex operations, the shortcomings of this approach gradually manifested, such as settimeout to get the value of the incorrect, or the page has a complex operation is easily triggered by the false dead state, asynchronous code will affect the main thread of the code execution, asynchronous is still a single-threaded, can not Asynchronous code will affect the main thread code execution.
Web Worker was created as part of the HTML5 standard, which defines a set of APIs that allow a JavaScript program to run in a thread other than the main thread. Some tasks are assigned to the latter. While the main thread is running, the Worker (child) thread runs in the background without interfering with each other. When the worker thread finishes its computation, it returns the results to the main thread. The advantage of this is that some computation-intensive or high-latency tasks are taken care of by the worker thread, and the main thread (which is usually responsible for the UI interactions) will be smooth and will not be blocked or slowed down.
I. What is a web worker
worker is a method of the window object, you can check if your browser supports worker by doing the following
if (window.Worker) {…… your code ……}
A worker is an object created using a constructor (Worker()) that needs to be passed a JavaScript file containing the code that will be run in the worker thread. Something like this:
let myWorker = new Worker('worker.js');
The worker communicates data through the postMessage() method and the onmessage event. The main thread and child threads are bi-directional and both can send and listen to events. Sending a message to a worker requires this (main.js):
myWorker.postMessage('hello, world');
worker.onmessage = function (event) {
console.log('Received message ' + event.data);
doSomething();
}
All data passed by postMessage is passed as a copy (except for ArrayBuffer types), and data subthreads are passed similarly (worker.js)
addEventListener('message', function (e) {
postMessage('You said: ' + e.data);
}, false);
When the subthread has finished running and is used up, it can be closed manually to save system resources. If the worker is not listening for messages, it will be closed automatically when all tasks are executed (including counters).
worker.terminate();
close();
worker.addEventListener('error', function (e) {
console.log('ERROR', e);
});
The web worker itself is simple, but it is particularly limited.
II. Issues of utilization
1. Homologation restrictions
The script file (worker.js) assigned to the worker thread to run must be from the same source as the main thread’s script file (main.js). The same-origin restriction here includes protocol, domain and port, and does not support local addresses (file://). This will bring a problem, we often use CDN to store the js file, the main thread of the domain of the worker.js refers to the html file is located in the domain, loaded through the new Worker (url) url belongs to the CDN domain, will bring the cross-domain problem, the actual development of we will not be put in a file to let the subthread to load all of the code, will certainly choose the Modular development. Through tools or libraries to merge the code into a file, and then sub-threaded code to generate a file url.
Solution:
(1) Convert dynamically generated scripts into Blob objects.
(2) Then create a URL for this Blob object.
(3) Finally, pass this created URL as an 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);
2. Access restrictions
The global object where the worker sub-thread is located is not in the same context as the main thread, so it can’t read the DOM objects of the web page where the main thread is located, and it can’t use the objects of document, window, parent, the point of the global object has been changed, and the window needs to be rewritten as self, and it can’t execute the methods of alert() and confirm(), and it can only read part of the data in the navigator object. confirm() method, and can only read part of the data in the navigator object. In addition, chrome’s console.log() can be used, and also supports debugger breakpoints, increasing the convenience of debugging.
3、Use of asynchronous
AJAX requests can be made in the worker subthread using the XMLHttpRequest object, using the setTimeout() setInterval() method, or using websocket for persistent links. It is also possible to load another script file via importScripts(url), but still not cross-domain.
III. Application scenarios
1. Use dedicated threads for math operations
Web Worke is designed to be used to do time-consuming tasks , big data processing , and this calculation is placed in the worker will not interrupt the front-end user operations , to avoid code lag brings unnecessary user experience . For example, to deal with ajax return of large amounts of data , read the user uploaded files , calculate MD5, change the bitmap of the canvas filter , analyze video and audio files , etc. In addition to the missing worker DOM and BOM manipulation capabilities , but also has a very powerful js logic processing capabilities , equivalent to nodejs a level of the operating environment .
2、High frequency user interaction
High-frequency user interaction is suitable for assisting users in completing input error correction and correction functions based on user input habits, history and cache information, etc. The response processing of frequent user input can also be considered to be executed in the web worker. For example, we can make an application like Word: when the user is typing, the background will look up in the dictionary, and help the user to correct errors automatically, and so on.
3. Prefetching of data
For some products with a large amount of data on the front and back of the interactive products, you can open a new thread dedicated to data prefetching and buffering data, local web database rows to write and change, a long time to run continuously, will not be interrupted by activities on the main thread (such as the user clicks a button, submit a form), but also conducive to responding to the main thread at any time to the communication. Can also be used with XMLHttpRequest and websocket for constant open communication, the realization of the guard process.
IV. Compatibility
Overall, the compatibility is still good, mobile can be used with confidence, desktop requirements are not too high, you can also use.
V. Summary
For the web worker this new technology, no matter in the PC or in the mobile web, tencent news front-end group carried on the extensive use, the realization of the Web Worker for the front-end program to bring the ability of the background calculation, can realize the main UI thread and the separation of complex computing thread, which greatly reduces the amount of computation due to the UI blocking caused by the emergence of the interface rendering of the card, dropped frames and greater use of terminal hardware performance. superWorker can solve the problem of event binding, the same source policy. SuperWorker can solve the problems of event binding and same-origin policy, but its biggest problem is that it is not compatible with IE9, so use it as much as possible where compatibility requirements are not so strict!