Welcome to a tutorial on how to create an offline app in Javascript. So you have heard of Web 3.0, where things get funky, decentralized, and offline. But just how do we create an offline app?
A basic offline Javascript app consists of:
- Saving all the core files in the client’s storage cache.
- Register a service worker that will fetch the files from the storage cache, instead of the server.
Yep, that covers the super quick basics. Read on for a “Hello Offline World” example!
TLDR – QUICK SLIDES
[web_stories_embed url=”https://code-boxx.com/web-stories/javascript-offline-web-app/” title=”Simple Javascript Offline Web App” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]
Fullscreen Mode – Click Here
TABLE OF CONTENTS
OFFLINE WEB APP WITH JAVASCRIPT
All right, let us now get into the example of creating an offline web app with Javascript.
STEP 1) THE HTML
<!-- (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>
<!-- (B) CONTENT AS USUAL -->
<h1>Hello Offline World!</h1>
Nothing out of the blue here, just your regular HTML page. But take note that we are registering a service worker in the <head>
section.
P.S. Take extra note that we need https://
to properly register a service worker, http://localhost
is an exception for testing and development.
STEP 2) THE SERVICE WORKER
// (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))
});
What the heck is a service worker and what does it do? In simple terms, a service worker runs in the background, and it is capable of all sorts of things – Caching and serving files, showing notifications, checking and receiving updates, etc… Yes, service workers can run even after the user closes the webpage. As to what is happening here:
- (A) On the first visit, this
install
part will run. All it does is save the defined files list into the cache storage. Note – This is not the browser cache, but a separate app cache that is persistent. - (C) “Hijack” all fetch requests. Serve the cached copy if found, or fallback to fetch from the server. In short, going offline using the cache.
STEP 3) VERIFY OFFLINE LOADING
Yes, we are done. Sorry to the guys who are expecting “crazy hacker stuff”. You can now do a quick verification of this by firing up the developer’s console. This is Google Chrome, but all Chromium-based browsers should be the same, and Firefox/Safari should have the same testing tools:
- Load the page first, the service worker should register. You check under the “Application” tab, service workers.
- Then go under the “Network” tab, and set the network speed to “offline”.
- Reload the page. The waterfall diagram should show that the
1-main.html
is being served by the service worker – The cached copy that is.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
STILL LOST?
For the guys who are still lost with “there’s no example app here” – Simply cache all your project files (HTML, CSS, JS, images, audio, video) in 2-service-worker.js
. Yes, an “offline app” is that simple. We pretty much save a copy of the entire project into the browser, so it can run locally like an “installed app”.
AN OFFLINE APP IS NOT A PROGRESSIVE WEB APP
Congratulations, you have created your first offline web app. But please don’t confuse this with a PWA, this is NOT a PWA. According to the 3 principles of Web App, a PWA should be:
- Capable – Store data, live chat, video, whatever else funky functions.
- Reliable – Still usable while offline, has fallback options for older browsers.
- Installable – Can be installed.
Yes, we have fulfilled the “offline capability” part, but there are plenty more to address before you can call this a “PWA”.
OFFLINE STORAGE
Now that you know how to cache files for offline use, here’s a small highlight on the options for storing data on the client side for offline use.
- Cache Storage (as above)
- Local Storage
- Indexed Database
Do a quick research on your own, or shameless self-promotion – Check out my Breakthrough Javascript eBook. Download the preview, the first few chapters are free.
COMPATIBILITY CHECKS
- Arrow Functions – CanIUse
- Service Workers – CanIUse
- Cache Storage – CanIUse
Offline apps will only work on modern “Grade A” browsers.
LINKS & REFERENCES
- Very Simple PWA Example – Code Boxx
- Need more offline PWA examples? Just do an “offline app” search right here on Code Boxx.
- Progressive Web App – web.dev
- Service Worker – MDN
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Very helpful article, thanks a lot!