Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

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

    Chris AchardChris Achard
    reactReact
    16.6.3-16.8.6
    javascriptJavaScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: 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.

    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.

    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.

    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.

    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.