AMP
  • websites

amp-install-serviceworker

Introduction

The amp-install-serviceworker component enables service worker installation via same origin or via the Google AMP Cache.

Service workers can run in the background even when the browser is closed, cache required contents in advance of rendering time, send notifications to users, and more.

This sample installs a service worker which caches this page in the background. You can test this by loading this page while offline once the service worker has been installed.

Service Workers are currently available in Chrome, Edge, Firefox, Opera and Safari.

The AMP Project provides a drop in service Worker to help your AMP pages gain network resiliency in one line.

Setup

Import the amp-install-serviceworker component.

<script async custom-element="amp-install-serviceworker" src="https://cdn.ampproject.org/v0/amp-install-serviceworker-0.1.js"></script>

Installing the service worker

Calls to amp-install-serviceworker can include the src and data-iframe-src attributes. src is the location of the service worker to be installed, and is used when the document is accessed via the same origin as the service worker file. When the document is accessed via the Google AMP Cache, the HTML document noted in the data-iframe-src attribute is used to install the service worker. We recommend using both attributes.

The reason why amp-install-serviceworker requires a separate data-iframe-src option is because browsers can't install service worker from other domains for security reasons. For details of the security considerations of service worker, see official specs.

If you don't want to provide a special minimal document to install a sevice worker, you can simply link to the AMP document on your own origin.

<amp-install-serviceworker
    src="/serviceworker.js"
    data-iframe-src="https://amp.dev/serviceworker.html"
    layout="nodisplay">
</amp-install-serviceworker>

In this sample, when users access this AMP page for the second time, the service worker is installed and caches all image files and video files under the root path of this domain.

Confirm that the service worker is installed and works as expected by following the following steps:

  1. Access amp-install-serviceworker twice.
  2. Open Chrome Dev Tools and navigate to the "Resources" tab (or "Application" tab on newer versions of Chrome). In the "Service Workers" section you can see that /sw.js is installed.
  3. Then open the "Cached Storage" section. It shows all cached images and videos.
  4. Disable your network connection and reload this page. It still works! In the "Network" tab in Dev Tools, you'll see which resources are cached by the service worker.
자세한 설명이 필요하신가요?

이 페이지의 설명만으로 궁금한 점이 모두 해결되지 않는다면 다른 AMP 사용자에게 문의하여 구체적인 활용 사례를 논의해 보세요.

Stack Overflow로 이동
설명이 부족한 기능을 발견하셨나요?

AMP 프로젝트는 여러분의 참여와 기여를 적극 환영합니다! 오픈 소스 커뮤니티를 통해 지속적으로 활동해 주셔도 좋지만 관심 있는 주제에 한 번만 기여하셔도 큰 도움이 됩니다.

GitHub에서 샘플 수정하기