DEV Community

Andrés Álvarez Iglesias
Andrés Álvarez Iglesias

Posted on

PWA and Django #3: Online and offline resources in a PWA - Developing Progressive Web Applications with Django

NOTE: First published in: https://andresalvareziglesias.substack.com/p/pwa-and-django-3-online-and-offline

Welcome to the third entry on the Progressive Web Application with Django series. In this chapter, we'll learn how to cache resources for our PWA to be able to use them offline, without an active internet connection.

Online and offline resources in a PWA - Developing Progressive Web Applications with Django

Implementing Offline Functionality

In the previous chapters we defined an small PWA application with every required part: the manifest and the ServiceWorker. We learned how to register the PWA and developed a very simple interface with some images:

A very simple interface with some images for our demo PWA

Now we will learn how to store data in the PWA cache and how to choose from where to load every image: from the internet or from the local cache.

To store one or more resources on the PWA cache we use a function like this on the ServiceWorker:

const CACHE_NAME = "DJANGO_PWA_TEST"
const MAIN_URL = "https://laboratorio.alvarezperello.com/djangopwa/";

self.addEventListener("install", (event) => {
   console.info("*** PWA event *** install", event);
   event.waitUntil(activateApp());
});

self.addEventListener("activate", (event) => {
   console.info("*** PWA event *** activate", event);
   event.waitUntil(activateApp());
});

async function activateApp() {
   // When a service worker is initially registered, pages won't use it
   // until they next load. The claim() method causes those pages to be
   // controlled immediately.
   console.log('Claiming control...');
   clients.claim().then((ev) => {
       console.log('...claimed!', ev);
   })

   manageCache();
}

self.addEventListener("sync", (event) => {
   console.info("*** PWA event *** sync", event);
   manageCache();
});

async function manageCache() {
   const cache = await caches.open(CACHE_NAME);
   if (!cache) {
       console.error("Error storing resources in cache!");
       return;
   }

   storeResourceInCache(cache, MAIN_URL+"static/demo/img/snake1.jpg");
   //storeResourceInCache(cache, MAIN_URL+"static/demo/img/snake2.png");
   //storeResourceInCache(cache, MAIN_URL+"static/demo/img/snake3.png");
}

async function storeResourceInCache(cache, element) {
   console.log("Storing resource in cache: "+element);
   cache.add(element).then(event => {
       console.info("Resource stored successfully! "+element);
   }).catch(event => {
       console.error("Error storing resource! "+element, event);
   });
}
Enter fullscreen mode Exit fullscreen mode

Now, when we execute our PWA, we can read the cache messages in the developer console:

Registering service worker...
...register completed!
The service worker is active!

serviceworker.js: Claiming control...
serviceworker.js: Resource already in cache! static/demo/img/snake1.jpg
Enter fullscreen mode Exit fullscreen mode

Our PWA cache is working!

Choosing from where to load each resource

When the PWA loads a resource, calls the fetch event, like this:

self.addEventListener("fetch", async (event) => {
   console.info("*** PWA event *** fetch", event);

   let url = event.request.url.toString();
   console.info("The PWA is loading a resource from: "+url);
});
Enter fullscreen mode Exit fullscreen mode

We are in control of the request now, and can choose from where return the requested resource: from cache or from internet.

Here is an example of how to check if we have a resource cached and return it from cache. And, if not cached, request it from the Internet instead.

self.addEventListener("fetch", async (event) => {
   let url = event.request.url.toString();
   if (!url.includes("static/demo/img/snake")) {
       return false;
   }

   const cache = await caches.open(CACHE_NAME);
   if (!cache) {
       console.error("Error loading resources from cache!");
       return false;
   }

   let fetchResponsePromise = await cache.match(url).then(async (cachedResponse) => {
       if (cachedResponse && cachedResponse.ok) {
           console.warn("Loading from cache: "+url);
           return cachedResponse;

       } else {
           console.error("Error! the cache does not have this url! "+url);
           console.error(cache.keys());

           remoteFetchResponsePromise = await fetch(event).then(async (networkResponse) => {
               console.warn("Loading from internet: "+url);
               return networkResponse;
           });

           return remoteFetchResponsePromise;
       }
   });

   return (await fetchResponsePromise);
});
Enter fullscreen mode Exit fullscreen mode

We can read the developer console to know from where every image has been loaded, like this:

From where our PWA loads every image: cache or internet

In the next chapter

We now have a PWA. Now we will learn how to make an installable PWA, that will show as a native application in the operating system. That's one of the greatest functionalities of the PWAs: we can use them to create "almost native" applications using Django.

See you in the next chapter!

About the list

Among the Python and Docker posts, I will also write about other related topics, like:

  • Software architecture
  • Programming environments
  • Linux operating system
  • Etc.

If you found some interesting technology, programming language or whatever, please, let me know! I'm always open to learning something new!

About the author

I'm Andrés, a full-stack software developer based in Palma, on a personal journey to improve my coding skills. I'm also a self-published fantasy writer with four published novels to my name. Feel free to ask me anything!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay