preface

The normal opening phrase would be “What is a Service Worker?” but Service workers are often mentioned in conjunction with PWA. Whether you’re in front of a screen with a lot of experience developing PWA, or if you’ve never heard of the concept before, it’s your duty to explain the relationship between Service workers and PWA, assuming you’re just a front end engineer who’s interested in Service workers and doesn’t have a lot of experience. This is not a tech-savvy article. If you just want to learn how certain apis work, or if you have a problem that needs to be solved, this article will take you 5-20 minutes

From the PWA

PWA stands for Progressive Web Apps, which literally translates as “Progressive Web applications.” This translation should not be accepted by most people, because we don’t take PWA literally. Here’s how Wikipedia defines a PWA:

Progressive Web Apps (PWA) is a common Web application or Web site architecture, but it can be presented to users in the form of traditional applications or native mobile applications.

This is also a correct but inadequate definition and does not well describe the true nature of the PWA.

After a period of sorting out, I would like to express my understanding of PWA in this paper: I understand both Web and App, but what does Progressive mean? Speaking of Progressive, you’ve heard a lot about the idea of “steady degradation, Progressive enhancement” for Web applications. Because browsers tend to lag (or even not follow) Web standards, many good new features are not supported by older browsers. So developers sometimes take an incremental approach, taking full advantage of new features and providing improved functionality and a better experience for browsers that support them (get some rich first?). . The P of PWA, that’s roughly what it means. As we all know, Web applications and Native applications have their own application scenarios and advantages. However, with the advent of the grandiose mobile Internet era, greedy human beings want to learn from each other and take into account the advantages of both, so they are happy to invent lump after lump of rotten tail mixed development technology with impure bloodline, which is not listed here, everyone understands. PWA is another attempt to achieve the same goal. It is by no means a revolutionary technology. It is just another crazy test from traditional Web applications to Native applications, and it is just a modest evolution. But unlike hybrid development technologies, PWA is a natural extension of pedigree Web technologies, backed by relevant Web standards.

This time around, PWA are stronger than traditional Web applications in a number of ways:

  • Look and feel: On mobile, you can add Web apps to the desktop and provide an immersive experience similar to Native apps. The technology behind this is Manifest, which is not the focus of this article, although it can bring a whole new experience.
  • Performance: Since the Service Worker in this article has the super ability to intercept HTTP requests from browsers, PWA, combined with CacheStorage, can improve the user experience and performance of Web applications when network conditions are poor or even offline.
  • Other aspects: Optional advanced features such as push notifications and background synchronization, which are also implemented using Service workers.

Simple summary: The PWA is the natural evolution of Web applications, and Service workers are key to the PWA.

At this point, this article seems to be off topic, so let’s get back to the Service Worker

A Service Worker is a script written in JavaScript that the browser runs in the background independently of the web page. Let’s take a look at what the smallest Service Worker looks like, and how it works :(please don’t skip it when you see a block of code, believe me, there are really few lines)

// The "if" line, in addition to preventing errors, also inadvertently explains the P of the PWA:
// If the browser does not support Service workers, what if nothing happened
if ('serviceWorker' in navigator) {
    window.addEventListener('load'.function () {
        // So the Service Worker is just an HTML5 API that hangs on the Navigator object
        navigator.serviceWorker.register('/service-worker.js').then(function (registration) {
            console.log('I have successfully registered 666');
        }, function (err) {
            console.log('I failed to register');
        });
    });
}
Copy the code

The above code, after the load event is triggered, downloads and registers the service-worker.js file. The service worker logic is written here:

// service-worker.js
// While you can write any js code you want in it, or you can write none at all,
// This is not a Service Worker, but here is a small example:
self.addEventListener('fetch'.function (event) {
    if (/\.png$/.test(event.request.url)) {
        event.respondWith(fetch('/images/ alipay payment code.png ')); }});Copy the code

TL big brother desktop scan code demand alipay QR code inspired by behind, the above code, can block the page all PNG picture request, return your Alipay collection code picture, as long as the user is enough, there will always be someone to give you money. Self is the first weird part of the code. It looks like an undefined variable, but after a little thought we realize that it’s a keyword, like window or global, that represents the Service Worker itself, so if we want to play with the Service Worker, You have to learn the API. Instead of looking at the apis that need to be memorized, just remember what this code does. It acts like a middleware that blocks and processes HTTP requests, and the Service Worker, in this case, acts as a client proxy. Because the code is written by humans, it opens up endless possibilities. In addition, the worst thing is that a gangster knows martial arts, so the Service Worker asks for HTTPS. Note the “S”, except for localhost for development and debugging purposes.

Simple summary:

  • We need to manually write the service-worker.js file.
  • We need to download and register the service-worker.js file from the web page.
  • Service workers have the ability to intercept and process HTTP requests.

Life cycle of a Service Worker

According to an article always beat, to this stage of the in-depth reading experience often suddenly becomes poor, in order to avoid this kind of situation, have to mention the Service Worker life cycle, recommend to read elsewhere, this article has a lot of, in this paper, the author thinks that can write but it is not necessary to here, and have no confidence to write better than they, If it is written, there is the suspicion of plagiarism, so I just post the picture of MDN here, and a simple summary (smile).


  • Service Worker lifecycle: install, install, activate, activate, I waste. (Kind of like component lifecycle, isn’t it?)
  • When navigating to the website for the first time, the Service Worker file will be downloaded, parsed and executed, and the install event will be triggered to try to install the Service Worker. If all operations in the callback function of the install event are successfully executed, the Service Worker is successfully installed. In the waiting state, notice that the Service Worker is only ready and has not taken effect. The Service Worker will be activated when the user enters the site a second time, and the activate event will be triggered to signal that the Service Worker is officially started. The fetch, POST, and SYNC events are started.

The main event of the Service Worker

  • Install: As the name suggests, the Service Worker fires when it is installed, which is usually when files are cached.
  • Activate: As the name suggests, this is triggered when the Service Worker is activated. This is usually the time to do something to reset the Service Worker, such as handling the cache of the older version of the Service Worker.
  • Fetch: As the name suggests, triggered when the browser makes an HTTP request, usually matching the cache in the callback function for this event, is the most commonly used event.
  • Push: As the name implies, it is related to the push notification function. If there is no relevant requirement, you can not learn about it.
  • Sync: As the name implies, it is related to the background synchronization function. If there is no relevant requirement, you can not learn about it.

Application of the Service Worker

Once we’ve mastered the basics of the Service Worker, it’s time to try it out. Here’s a look at some of the applications that are related to web performance, not paste code, but ideas and methods.

1. Cache static resources

A great application for Service workers is the CacheStorage API to cache js, CSS, fonts, images, and other static files. In the install phase of the Service Worker, we can specify the specific file to be cached and check the requested URL in the callback function of fetch event. If the url matches the cached resource, it will no longer be obtained from the server, so as to improve the performance of the web page. The commonly used App Shell architecture for building PWA is implemented in this way. It is important to note that the performance improvement is relative to no caching at all, and the browser itself has a relatively good HTTP caching mechanism. So instead of delivering an immediate performance boost to our already relatively sophisticated architecture, the real significance of Service Worker caching is that it allows more precise, coded control over how to cache, what to cache, and how to update the cache. It all depends on how the code is written, so this provides a lot of freedom, but it also comes with maintenance costs. It’s just a new way of caching, not a breakthrough from scratch.

2. Offline experience

In the previous section, we only cached static resources such as JS, CSS, fonts, images, etc., but what if we also cached the home page index.html? It turns out that our web pages can even support offline browsing. Sounds great, right? Please sit down. Here’s a huge question: If our home page is index.html, and the service worker. Js is registered in it, and the index.html is cached in the service worker. Then the problem is that the next time we go online, the dead or alive will not take effect. Is it awkward because the user is always accessing the cached index.html? We need to update service-worker.js to cache index.html again, and while there are some solutions to this problem online, it seems so confusing that it makes us wonder if offline browsing makes sense. Now that we have the ability to cache files offline and block HTTP requests, we can cache an offline.html page, similar to a 404 page, when the Service Worker is installed. When we are offline, our requests to access the index.html file will fail, so we return to the offline.html file and present it to the user. Depending on the specific requirements, we can even play a little game like chrome does when it is offline to play with users who are not connected.

3. The other

The Service Worker just provides some awesome features, but it’s up to the developer to use it, and with a lot of imagination, it’s possible to provide a refreshing experience. Here is just a small example: as we know, images in web pages are very bandwidth consuming, users are waiting for the site to load, many times are waiting for images, and most of the images placed on the CDN, support to add suffix parameters to obtain different resolution photos function. Suppose we have a way to know whether a user’s network condition is good or bad (as for how to judge a user’s network condition, is another matter, can let the user choose, also can use technical means to solve), classify the users, for a moment, into two levels: fast network and slow network. We put the network speed level information in the HTTP request header (or wherever you want). When we make the image request, we have the opportunity to get the user’s network level. If the user has a fast connection, we return the high resolution image on the CDN with the suffix parameter, and vice versa. The result was that users with fast Internet connections saw sharper photos, while those with slow Internet connections saw photos with less clarity but earlier, without having to wait a long time.

Matters needing attention

The above discussion is all on paper, when we really want to use in the production environment, think carefully, we will find that things are not so simple, here are some need to pay attention to and consider the place.

  • The first thing we need to do is buy the regret pill. Because Service workers are doing dangerous things on strange clients anyway, if something goes wrong (and it will), it’s usually not a bug, but an incident level. In that case, we’ll probably need another company to continue experimenting with our lovely Service Worker. The idea is to provide the switch interface somewhere like a configuration center, or on the server, call the interface in front of the request page, and if something goes wrong, turn off the switch and trigger the destruction of the Service Worker’s code.
  • If the project is iterated, then the QA student’s browser environment will be different from the real user’s browser environment at the time of project testing, or at least not fully covered. The existence of a Service Worker essentially turns an already stateful client into a more stateful client. As a result, some bugs may not be detected during the testing phase and are visually difficult to reproduce, debug, resolve, and verify.

Application scenarios

Let’s talk about the Service Worker scenario, or what needs to happen to a Service Worker. It makes sense, but it’s important that we don’t hold a hammer and look at everything like a nail.

  • Site functionality tends to stabilize: Sites that iterate frequently seem to have trouble adding Service workers.
  • The site needs a large number of users: management background, OA system and other scenarios do not seem to be very necessary to add a Service Worker.
  • Sites are really after user experience: Buggy, ugly sites don’t seem to need Service workers very much.
  • Site user experience is about retention: 12306 doesn’t seem to need a Service Worker at all.
  • Wait, wait, wait…

Simple summary: The original purpose of the Service Worker is to optimize the user experience to the extreme. It is designed to be the icing on the cake. Technology is just technology, but the cost and benefit should be considered before the actual application.

Some nonsense

This article briefly talks about the relationship between PWA and Service Worker, the foundation of Service Worker, the life cycle and events of Service Worker, the simple application of Service Worker, as well as matters needing attention and scenarios in practical application. It is just an entry level popular science article. You can learn more about it, depending on what you are interested in. Given that the author of this article is a talented and uneducated troll, it is inevitable that some omissions and even misleading, welcome to correct.

In addition, in the process of code words, there are some impressions to share with you here:

  • Service Worker and PWA has appeared about 4 years or so, but appears to have been a failed to hit the state, also can’t see what the outbreak of the trend, the reason may be that various, but the single biggest reason, however, may be not to push the huge demand, truly has the potential to technology, it must be you don’t feel learn all mixed up.
  • The essential difference between Web applications and Native applications is whether the compiled product is placed on the server or client. Static resources of Web applications need to be obtained from the server, which is a major cause of poor Web application experience. The browser’S HTTP cache, and the Service Worker’s cache, are both compromise solutions, at least not to the problem of slow first-screen loading.
  • As the 5G era is coming, is the performance of Web applications still a problem? Are the hundreds of milliseconds of performance gains that Service workers might provide meaningful? When most people’s network conditions have reached a new level, perhaps web pages will no longer be stuck for a few seconds, and apps can be downloaded in an instant, then will we really bother with caching? Will web pages and apps still exist?

At this point, this post is off topic, but Service workers are perfect for bragging, and if they’re going to be used on a large scale, they might need to be considered in context. However, as a technical reserve is still necessary. Anyway, the takeout is cold. Then what are you still doing here? Please like, comment and bookmark it!

About us

Fast dog taxi front-end team focus on front-end technology sharing, regularly push high-quality articles, welcome attention like.