InstallEvent

我们的志愿者还没有将这篇文章翻译为 中文 (简体)加入我们帮助完成翻译!
您也可以阅读此文章的English (US)版。

This is an experimental technology
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the specification changes.

The InstallEvent interface represents an install action that is dispatched on the ServiceWorkerGlobalScope of a ServiceWorker. As a child of ExtendableEvent it ensures that functional events (like FetchEvent) are not dispatched during installation. 

Properties

Inherits properties from its ancestor, Event.

Methods

Inherits methods from its parent, ExtendableEvent.

Examples

This code snippet is from the service worker fetch sample. The code calls ExtendableEvent.waitUntil(any value) in ServiceWorkerGlobalScope.oninstall, delaying treating the ServiceWorkerRegistration.installing worker as installed until the passed promise resolves successfully. The promise resolves when all resources have been fetched and cached, or else when any exception occurs.

The code snippet also shows a best practice for versioning caches used by the service worker. Though there's only one cache in this example, the same approach can be used for multiple caches. It maps a shorthand identifier for a cache to a specific, versioned cache name.

Note: Logging statements are visible via the "Inspect" interface for the relevant SW accessed via chrome://serviceworker-internals.

var CACHE_VERSION = 1;
var CURRENT_CACHES = {
  prefetch: 'prefetch-cache-v' + CACHE_VERSION
};
self.addEventListener('install', function(event) {
  var urlsToPrefetch = [
    './static/pre_fetched.txt',
    './static/pre_fetched.html',
    'https://www.chromium.org/_/rsrc/1302286216006/config/customLogo.gif'
  ];
console.log('Handling install event. Resources to pre-fetch:', urlsToPrefetch);
  event.waitUntil(
    caches.open(CURRENT_CACHES['prefetch']).then(function(cache) {
      cache.addAll(urlsToPrefetch.map(function(urlToPrefetch) {
        return new Request(urlToPrefetch, {mode: 'no-cors'});
      })).then(function() {
        console.log('All resources have been fetched and cached.');
      });
    }).catch(function(error) {
      console.error('Pre-fetching failed:', error);
    })
  );
});

Specifications

Specification Status Comment
Service Workers
The definition of 'FetchEvent' in that specification.
Working Draft Initial definition.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 40.0 No support No support 24 No support
Feature Android Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support ? No support No support No support ? No support 40.0

See also

文档标签和贡献者