What is a fetch event?

Technology CommunityCategory: PWAWhat is a fetch event?
VietMX Staff asked 5 months ago

After a service worker is installed and the user navigates to a different page or refreshes, the service worker will begin to receive fetch events.

fetch event fires every time any resource controlled by a service worker is fetched, which includes the documents inside the specified scope, and any resources referenced in those documents (for example if index.html makes a cross origin request to embed an image, that still goes through its service worker.)

Consider:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        }
        return fetch(event.request);
      }
    )
  );
});