ServiceWorkerGlobalScope: sự kiện install

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2018.

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

Note: This feature is only available in Service Workers.

Sự kiện install của giao diện ServiceWorkerGlobalScope được kích hoạt khi một ServiceWorkerRegistration có một worker ServiceWorkerRegistration.installing mới.

Sự kiện này không thể hủy và không nổi bọt.

Cú pháp

Sử dụng tên sự kiện trong các phương thức như addEventListener(), hoặc thiết lập một thuộc tính trình xử lý sự kiện.

js
addEventListener("install", (event) => { })

oninstall = (event) => { }

Loại sự kiện

Một ExtendableEvent. Kế thừa từ Event.

Event ExtendableEvent

Thuộc tính sự kiện

Không triển khai bất kỳ thuộc tính cụ thể nào, nhưng kế thừa các thuộc tính từ giao diện cha, Event.

Ví dụ

Đoạn mã sau đây cho thấy cách trình xử lý sự kiện install có thể được sử dụng để điền vào bộ nhớ đệm với một số phản hồi, mà service worker sau đó có thể sử dụng để phục vụ tài nguyên ngoại tuyến:

js
self.addEventListener("install", (event) => {
  event.waitUntil(
    caches
      .open("v1")
      .then((cache) =>
        cache.addAll([
          "/",
          "/index.html",
          "/style.css",
          "/app.js",
          "/image-list.js",
          "/star-wars-logo.jpg",
          "/gallery/",
          "/gallery/bountyHunters.jpg",
          "/gallery/myLittleVader.jpg",
          "/gallery/snowTroopers.jpg",
        ]),
      ),
  );
});

Bạn cũng có thể thiết lập trình xử lý sự kiện bằng cách sử dụng thuộc tính oninstall:

js
self.oninstall = (event) => {
  // …
};

Đặc tả kỹ thuật

Specification
Service Workers Nightly
# dom-serviceworkerglobalscope-oninstall

Tương thích trình duyệt

Xem thêm