Skip to main content

Web API

Aworker implements a specification similar to Service Worker API, providing a basic Request-Response service API.

addEventListener('fetch', event => {
event.respondWith(new Response('hello world'));
});

Aworker provides common Web APIs defined in ServiceWorkerGlobalScope, WorkerGlobalScope or WindowOrWorkerGlobalScope. Typically, this includes the following web APIs:

Aworker lifecycle

Aworker will have the following events from loading user code initialization to starting to receive requests:

  • 'install': The first event received after the user code is fully loaded. The program can start loading the cache in this event.
  • 'activate': Represents that Aworker is ready to receive requests.
  • 'fetch': Represents a request event.

There will be no events until the Worker instance is destroyed. It is usually guaranteed by the runtime that the Worker instance will be recycled after all requests have been responded to.

Aworker's events can be monitored through the Web EventTarget API, such as:

addEventListener('install', event => {
// initializing cache...
});

Event: 'install'

MDN: https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/install_event

Parameters:

The first event received after the user code is fully loaded

addEventListner('install', event => {
event.waitUntil(Promise.all([
cacheReady('http://example.com'),
]));
});

Event: 'activate'

MDN: https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/activate_event

Parameters:

Represents that the Worker instance is ready to receive requests.

addEventListner('activate', event => {
event.waitUntil(asyncOperation());
});

Event: 'fetch'

Parameters:

Represents a request event.

addEventListener('fetch', event => {
event.respondWith(new Response('hello world'));
});