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.
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:
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);
});
}
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
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);
});
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);
});
We can read the developer console to know from where every image has been loaded, like this:
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!
Top comments (0)