background

Why did I suddenly want to learn about Web workers? Because I saw an article on a certain website, and the article had a comment that the implementation of Web workers was very smooth. I was thinking about how to implement it, so I started to explore the journey of Web workers.

Read the MDN

Generally speaking, for the front-end domain to see a strange and familiar word, after searching, you can see the explanation of MDN, citing the classic, come up:

With Web Workers, a Web application can run a script operation in a background thread independent of the main thread. This has the advantage of being able to perform time-consuming processing tasks in a separate thread, allowing the main thread (usually the UI thread) not to block/slow down as a result.

There are obvious benefits to using Web workers, in that you can continue to run heavy computations without blocking the main thread, achieving performance gains (but not overuse, as discussed below).

Web Workers can be divided into Dedicated Workers, Shared Workers, Service Workers, Chrome Workers and audio Workers. The last two projects I am responsible for are not used in many scenarios, so I will not expand them. The first three Web Workers are introduced.

Dedicated Workers

Definition, use

Dedicated Workers use the Worker() constructor to create a Worker object. The constructor accepts a URL to a JavaScript file that contains the code to be run on the Worker thread.

// main.js
var myWorker = new Worker('./worker.js');

// worker.js, which contains tasks run by worker threads (performing computationheavy code)
onmessage = function(e) {
  console.log('Message received from main script');
  var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
  console.log('Posting message back to main script');
  postMessage(workerResult);
}
Copy the code

Start/run the Web Worker

First of all, the Worker thread cannot read local files, that is, it cannot open the local file system (file://), and the scripts it loads must come from the network. So if the local creates an HTML file and js files, directly in the browser to open the HTML file, a Web Worker is invalid, such as I opened the file:///Users/xxx/Desktop/aaa/aaa.html, The console will report an error if the js imported internally contains the Web worker-related JS code above

So if you want to debug locally, you need to serve the file, I use python command: python -m SimpleHTTPServer 8000.

Chrome Debug

Web Worker is implemented in the code and can indeed run normally. Then how can I know where the Worker is? How many workers are there in my page?

Open Chrome -> CMD+SHIFT+I -> Sources Tab -> Page to see how many Web workers there are and the scripts for specific Web workers.

Close the Web Worker

After use, the Worker must be shut down to save system resources.

/ / main thread
worker.terminate();
/ / Worker thread
self.close();
Copy the code

For Dedicated Workers, the shutdown means that the Sources TAB in Chrome will also disappear:

Shared Workers

Shared Workers are basically the same as Dedicated Workers, but may be more complicated. Shared Workers can be run by multiple scripts of different Windows, such as IFrames. Code examples 🌰 :

// main.js
if(!!!!!window.SharedWorker) {
  var myWorker = new SharedWorker("worker.js");

  first.onchange = function() {
    myWorker.port.postMessage([first.value, second.value]);
    console.log('Message posted to worker');
  }

  second.onchange = function() {
    myWorker.port.postMessage([first.value, second.value]);
    console.log('Message posted to worker');
  }

  myWorker.port.onmessage = function(e) {
    result1.textContent = e.data;
    console.log('Message received from worker');
    console.log(e.lastEventId); }}// worker.js
onconnect = function(e) {
  var port = e.ports[0];
  port.onmessage = function(e) {
    var workerResult = 'Result: ' + (e.data[0] * e.data[1]); port.postMessage(workerResult); }}Copy the code

In Chrome, the debug mode is also different. If you open Chrome ://inspect, you can see many navigations, including one called Shared Workers.

Service Workers

To be honest, the first Web Workers I came into contact with were Service Workers. There was a project that was used by Workers when they were working on the site. There was no network at the site, or the signal was very poor, so the requirements for offline were relatively high. However, it was a bit complicated to use and was not compatible with browsers at the time, so an alternative indexDB was used.

According to the documentation, the Service Worker can create a valid offline experience, intercept network requests, and take appropriate action to update resources residing on the server depending on whether the network is available.

The Angular framework implements the Service Worker, and there are some bugs in the framework (remember it was version 7, it may have been fixed by now, it has not used Angular πŸ˜… for a long time), which may affect the update if it is enabled. So far, I still don’t understand why Service Worker is enabled in that project. Everyone also needs to be offline.

It is also easy to debug in Chrome, in the Application TAB submenu:

Develop areas/limitations for attention

  1. As mentioned earlier, Web Workers cannot be run through local files, only through the network, otherwise they cannot be executed.
  2. Cognate: The script file assigned to the Worker thread must be cognate with the script file of the main thread.
  3. DOM limitations: While many people may be happy, can the performance bottleneck of page rendering be solved by Web Workers? Unlike the main thread, the global object where the Worker thread is located cannot read the DOM object of the page where the main thread is located, nor can document, window, parent objects be used.

However, there are many Web apis available in Web Workers, such as using XMLHttpRequest to access the Web, navigator objects and Location objects, so don’t despair, most of the apis are also available.

thinking

Although I have learned Web Workers and know how to use them, there are not many projects that use Web Workers to solve problems at present. I have found many libraries/tools to realize Web Workers through search engines. I am still optimistic about Web Workers.

Welcome to join us 🍺🍺🍺

References:

  • www.ruanyifeng.com/blog/2018/0…
  • Developer.mozilla.org/zh-CN/docs/…
  • Developer.mozilla.org/en-US/docs/…