Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Created July 2, 2023 01:28
Show Gist options
  • Save code-boxx/1b0e2405d87e81c0480e4ecf7fe5475d to your computer and use it in GitHub Desktop.
Save code-boxx/1b0e2405d87e81c0480e4ecf7fe5475d to your computer and use it in GitHub Desktop.
Javascript Offline Web App Example

JAVASCRIPT OFFLINE WEB APP EXAMPLE

https://code-boxx.com/offline-web-app-javascript/

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<!DOCTYPE html>
<html>
<head>
<title>Offline Web App Demo</title>
<!-- (A) REGISTER SERVICE WORKER -->
<script>
navigator.serviceWorker.register("2-service-worker.js")
.then(reg => console.log(reg)) // ok
.catch(err => console.error(err)); // error
</script>
</head>
<body>
<!-- (B) CONTENT AS USUAL -->
<h1>Hello Offline World!</h1>
</body>
</html>
// (A) CREATE/INSTALL CACHE
self.addEventListener("install", evt => {
self.skipWaiting();
evt.waitUntil(
caches.open("HelloOffline")
.then(cache => cache.addAll([
"1-main.html" // add more files to cache here
]))
.catch(err => console.error(err))
);
});
// (B) CLAIM CONTROL INSTANTLY
self.addEventListener("activate", evt => self.clients.claim());
// (C) LOAD FROM CACHE FIRST, FALLBACK TO NETWORK IF NOT FOUND
self.addEventListener("fetch", evt => evt.respondWith(
caches.match(evt.request).then(res => res || fetch(evt.request))
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment