Offline Web App Using Javascript (Very Simple Example)

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!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Offline App Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

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

1-main.html
<!-- (A) REGISTER SERVICE WORKER -->
<script>
navigator.serviceWorker.register("2-service-worker.js")
.then((reg) => { /* OK */ })
.catch((err) => { console.error(err); });
</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

2-service-worker.js
// (A) FILES TO CACHE
const cName = "HelloOffline",
cFiles = ["1-main.html"];
 
// (B) CREATE/INSTALL CACHE
self.addEventListener("install", (evt) => {
  evt.waitUntil(
    caches.open(cName)
    .then((cache) => { return cache.addAll(cFiles); })
    .catch((err) => { console.error(err) })
  );
});
 
// (C) LOAD FROM CACHE, FALLBACK TO NETWORK IF NOT FOUND
self.addEventListener("fetch", (evt) => {
  evt.respondWith(
    caches.match(evt.request)
    .then((res) => { return 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:

  1. We define the name of our cache storage, and the list of files to cache.
  2. On the first visit, this install part will run. All it does, is save the defined files into the cache storage. Note – This is not the browser cache, but a separate app cache that is persistent.
  3. “Hijack” all fetch requests. Serve the cached copy if found, or fallback to fetch from the server. In short, going offline using the cache.

 

 

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, 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.

 

USEFUL 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.

 

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

Not that you know how to cache files for offline use, how about storing data on the client-side? There are actually a few options:

  • Cache Storage (as above)
  • Local Storage
  • Indexed Database

Shameless self-promotion, check out my eBook – Breakthrough Javascript. The first few chapters are free previews.

 

COMPATIBILITY CHECKS

Offline apps will only work on modern “Grade A” browsers.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Simple Javascript Offline App (Click To Enlarge)

 

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!

1 thought on “Offline Web App Using Javascript (Very Simple Example)”

Leave a Comment

Your email address will not be published.