Skip to content

Instantly share code, notes, and snippets.

@shershen08
Created January 20, 2024 11:46
Show Gist options
  • Save shershen08/447e569cfef5b28892a01b17eac3b8b1 to your computer and use it in GitHub Desktop.
Save shershen08/447e569cfef5b28892a01b17eac3b8b1 to your computer and use it in GitHub Desktop.
Performance course v1 code samples
/**************
Lecture 1
/**************/
/**************
Lecture 2
/**************/
/**************
Lecture 3
/**************/
/**************
Lecture 4
/**************/
/**************
* Service Worker
* ************/
// inside the service worker an event handler is registered for the 'sync' event
// that sends the notification
self.addEventListener('sync', e => {
e.waitUntil(
self.registration.showNotification(title, options)
.catch(err => console.log(err))
)
});
// in the browser:
const syncButton = document.querySelector('#sync-button');
const registration = await navigator.serviceWorker.getRegistration();
if('sync' in registration) {
// the button doesn't actually send the notification, it only
// requests a synchronization that triggers a sync event inside
// the service worker when the network connection is available.
// This means that if the network connection is available
// when the button is clicked, the sync event handler inside
// the service worker will be called immediately and the notification
// will be sent. But when the button is clicked when there is no network
// the task will be deferred until the network connection is restored.
// At that point, the sync event will be fired and the notification will
// be sent.
syncButton.addEventListener('click', async () => {
await registration.sync.register('sync-demo');
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment