File tree Expand file tree Collapse file tree 6 files changed +59
-0
lines changed Expand file tree Collapse file tree 6 files changed +59
-0
lines changed Original file line number Diff line number Diff line change 1+ [ MDN Doc Link] ( https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers )
2+
3+ [ MDN Example Link] ( https://github.dev/mdn/dom-examples/tree/main/service-worker/simple-service-worker )
Original file line number Diff line number Diff line change 1+ <!DOCTYPE html>
2+ < html lang ="en ">
3+ < head >
4+ < meta charset ="UTF-8 ">
5+ < meta name ="viewport " content ="width=device-width, initial-scale=1.0 ">
6+ < link rel ="stylesheet " href ="style.css ">
7+ < title > Service Worker API</ title >
8+ </ head >
9+ < body >
10+ < button id ="sw-register "> Register Service Worker</ button >
11+ < script src ="script.js "> </ script >
12+ </ body >
13+ </ html >
Original file line number Diff line number Diff line change 1+ async function registerServiceWorker ( ) {
2+ if ( "serviceWorker" in navigator ) {
3+ try {
4+ const registration = await navigator . serviceWorker . register ( "/Service Worker API/sw.js" , {
5+ scope : "/Service Worker API/" ,
6+ } ) ;
7+ if ( registration . installing ) {
8+ console . log ( "Service worker installing" ) ;
9+ } else if ( registration . waiting ) {
10+ console . log ( "Service worker installed" ) ;
11+ } else if ( registration . active ) {
12+ console . log ( "Service worker active" ) ;
13+ }
14+ } catch ( error ) {
15+ console . error ( `Registration failed with ${ error } ` ) ;
16+ }
17+ }
18+ } ;
19+
20+ window . onload = function ( ) {
21+ const registerSwBtn = document . getElementById ( 'sw-register' ) ;
22+ registerSwBtn . addEventListener ( 'click' , registerServiceWorker ) ;
23+ }
Original file line number Diff line number Diff line change 1+ body {
2+ background-color : black;
3+ }
Original file line number Diff line number Diff line change 1+ const addResourcesToCache = async ( resources ) => {
2+ const cache = await caches . open ( 'v1' ) ;
3+ await cache . addAll ( resources ) ;
4+ } ;
5+
6+
7+ // Install and activate: populating your cache
8+ self . addEventListener ( 'install' , ( event ) => {
9+ event . waitUntil (
10+ addResourcesToCache ( [
11+ '/Service Worker API/demo.html' ,
12+ '/Service Worker API/style.css' ,
13+ '/Service Worker API/script.js' ,
14+ '/Service Worker API/image.png' ,
15+ ] )
16+ ) ;
17+ } ) ;
You can’t perform that action at this time.
0 commit comments