From 69733af6236e1e8ed0e3ee00c1a5bad33edf9796 Mon Sep 17 00:00:00 2001 From: Niels Reijn Date: Tue, 9 Feb 2021 17:07:45 +0100 Subject: [PATCH] Register Service worker --- exampleSite/config.toml | 5 +++++ layouts/partials/head.html | 4 ++++ layouts/partials/javascript.html | 9 +++++++++ static/sw.js | 1 + 4 files changed, 19 insertions(+) create mode 100644 static/sw.js diff --git a/exampleSite/config.toml b/exampleSite/config.toml index 46394ad84..a5b729358 100644 --- a/exampleSite/config.toml +++ b/exampleSite/config.toml @@ -61,6 +61,11 @@ disableHugoGeneratorInject = false homeSubtitle = "Hello Friend NG" + # Uncomment enableServiceWorker only if you have configured your site.webmanifest in the static folder. + # Check the documentation on how to generate a site.webmanifest. + # + # enableServiceWorker = true + # Set a background for the homepage # backgroundImage = "assets/images/background.jpg" diff --git a/layouts/partials/head.html b/layouts/partials/head.html index a855a5263..d9b6acda8 100644 --- a/layouts/partials/head.html +++ b/layouts/partials/head.html @@ -8,6 +8,10 @@ +{{- if .Site.Params.enableServiceWorker }} + +{{ end }} + {{ block "title" . }} {{ if .IsHome }} diff --git a/layouts/partials/javascript.html b/layouts/partials/javascript.html index 7b5f3a093..20ab5973c 100644 --- a/layouts/partials/javascript.html +++ b/layouts/partials/javascript.html @@ -13,3 +13,12 @@ <script src="{{ $val }}"></script> {{ end }} {{ end }} + +{{- if .Site.Params.enableServiceWorker }} + <script> + if('serviceWorker' in navigator) { + navigator.serviceWorker + .register('/sw.js', { scope: '/' }); + } + </script> +{{- end}} diff --git a/static/sw.js b/static/sw.js new file mode 100644 index 000000000..70c9b5dce --- /dev/null +++ b/static/sw.js @@ -0,0 +1 @@ +self.addEventListener('install',function(event){var indexPage=new Request('index.html');event.waitUntil(fetch(indexPage).then(function(response){return caches.open('pwabuilder-offline').then(function(cache){return cache.put(indexPage,response)})}))});self.addEventListener('fetch',function(event){var updateCache=function(request){return caches.open('pwabuilder-offline').then(function(cache){return fetch(request).then(function(response){return cache.put(request,response)})})};event.waitUntil(updateCache(event.request));event.respondWith(fetch(event.request).catch(function(error){return caches.open('pwabuilder-offline').then(function(cache){return cache.match(event.request).then(function(matching){var report=!matching||matching.status==404?Promise.reject('no-match'):matching;return report})})}))}) \ No newline at end of file