Listen for `install` and `activate` PWA Events in a Service Worker

Chris Achard
InstructorChris Achard
Share this video with your friends

Social Share Links

Send Tweet

Service workers are event-based, so we'll listen for the install and activate events, which will let us execute code when our PWA gets installed for the first time. We'll use setTimeout to simulate an asynchronous action and wait for that to complete, before allowing the PWA to continue installing.

Instructor: [00:01] In the sw.js file we can add a couple of listeners for the service worker life-cycle events, one for the install event and one for the activate event. Let's build and serve that. If we open a new tab to the console and load the app. They're the install and active events. Now if we reload again, notice that they don't show up.

[00:33] That's because the service worker is already installed and activated for this app, so those hooks won't fire again. We could go to the application tab and force and register the service worker. Now when we reload, we can see the new service worker was installed. In the console we can see the install and activate messages again, since a new service worker was installed.

[00:59] In these callbacks we could do actions like cleaning up old cached values or interacting with local storage or indexeddb. For now, we'll just put a set time out here to signify some asynchronous action. To make sure that install waits for the timeout to be complete however, we need to wrap it in a promise.

[01:20] Then we'll call a function or an event called waitUntil, and then pass in that promise. It's very important that whatever promise you pass in to waitUntil actually resolves or rejects. If we didn't resolve in the timeout here, it would wait forever to install the service worker. Then it would never activate. The service worker would never work.

[01:41] Let's build and serve that. In the application tab we can make sure the service worker is unregistered. Then if we switch to the console tab and reload, we'll see the install event. Then five seconds later we'll see the activate event.