Service workers are a powerful web technology that allows web applications to work offline and provide better performance. In this session, we will explore how to use service workers to make your UI5 application available offline.
We'll cover service worker basics, their capabilities, and how to register and cache essential assets (HTML, CSS, JS, and images) in your UI5 app. Next, we will dive into handling offline requests using the cached assets. We will discuss strategies for handling requests that are not cached, such as fallback mechanisms and offline-first design. We will also cover how to update the cached assets and service worker to ensure that your UI5 application remains up-to-date and reliable. For offline data storage and retrieval, we'll use the browser's local storage IndexedDB and cover how to use it with service workers in this session. Service workers offer offline caching and other background services to enhance UI5 applications, such as background fetch for downloading large files and background sync for data synchronization with a server when the network connection is available. Finally, we will discuss best practices for using service workers in UI5 applications, including performance considerations and security concerns.
By the end of this session, you will have a solid understanding of how to use service workers to make your UI5 application available offline and provide a seamless user experience, even when there is no internet connection available.
15. 15
Intercepting network requests
Responding with cached assets
Caching strategies:
Network only
Cache only
Network first
Cache first
Stale while revalidate
Caching assets for offline usage - fetch
event
My name is Klemen Volk, and I have had the privilege of working at Sapphir, for the past three years.
During my time at Sapphir, I have been involved in various projects, specializing in the creation of custom UI5 web applications.
One aspect that has captivated my attention is the ability to build web applications that seamlessly operate offline, thanks to the incredible capabilities of service workers.
In today's digital era, constant internet connectivity has become the norm. However there are still remote places with limited or no internet connection. So the ability for a web application to work without an internet connection has become crucial. The emergence of service workers, a powerful web technology has made this possible.
It is a key component of Progressive Web Applications (PWAs) and enables features such as caching, background services, and push notifications.
Service workers are event-driven scripts that act as a middle layer between the web application and the network and can intercept network requests, cache assets, and respond to offline requests. They provide a way to enhance the user experience by making the application available even when there is no internet connection.
Imagine a scenario where an employee in the warehouse has to take inventory of all the products with a web application that enables scanning the product and sends data to server. However somewhere in the back of the warehouse he lost the internet connection so the application crashes or displays an error.
If the web application developed with service worker to work offline he could scan all the products, the application would save them in local storage and when the internet connection is reestablished synchronize them with the server.
So the application would provide seamless user experience…
And it would maintain the core functionality (which is scanning) of the application.
Additionally, service workers can significantly improve performance by caching frequently accessed assets, reducing latency, and enhancing responsiveness.
Before implementing service workers in your web application, there are a few requirements to consider:
Browser support: Service workers are supported in most modern browsers, including Chrome, Firefox, Safari, and Edge. However, it's important to check the browser compatibility and versions to ensure that your target audience can benefit from the service worker functionality. Some older browsers may have limited or no support for service workers.
To use service workers in your web application, there are a few requirements to consider:
HTTPS or localhost: Service workers require a secure context to operate, which means they can only be registered on pages served over HTTPS. This requirement ensures the integrity and security of the service worker and the resources it controls. However, during development, you can register a service worker on localhost for testing purposes.
Fully async: It is designed to be fully async; as a consequence, APIs such as synchronous XHR can't be used inside a service worker.
Service worker file: You need to create a separate JavaScript file that will serve as your service worker. This file should contain the necessary code to control the caching, handling of requests, and other functionality you require. It's recommended to keep the service worker file separate from your main app code to maintain modularity.
Registration process: To enable a service worker in your web application, you need to register it within your index.HTML file. The registration process involves using the navigator.serviceWorker.register() method, passing the path to your service worker file as the parameter. This process establishes the link between your app and the service worker. In the registration process it’s recommended to set The scope of a service worker which determines the range of pages and assets it can control. Ensure that the scope encompasses the necessary resources for your app's offline functionality.
The lifecycle of a service worker consists of several key phases:
Registration
This is the initial step where you register the service worker in your web application.
Installation
install: This event is triggered when a new service worker is being installed for the first time.
You can listen to this event inside your service worker file to perform installation tasks, such as caching assets and setting up the initial state.
Activation
This event is triggered when the service worker is activated, either during the initial registration or when an updated service worker becomes active.
Use this event to handle activation tasks, such as cleaning up outdated caches, updating service worker versions, and ensuring the service worker takes control of the client pages.
Fetching and handling requests
This event is triggered whenever a network request is made from a client page controlled by the service worker.
Use this event to intercept and handle network requests. You can choose to respond with cached resources, fetch fresh resources from the network, or implement custom logic based on the request.
To make use of service workers in a UI5 application, the first step is to prepare your application for asynchronous loading of resources
Add the bootstrapping tag data-sap-ui-async="true" to your index.html file.
In manifest.json file set a parameter async=true in rootView and routing.config
Now that the UI5 application is prepared for asynchronous loading of resources, we can register the service worker.
To make use of service workers in a UI5 application, the first step is to prepare your application for asynchronous loading of resources
Add the bootstrapping tag data-sap-ui-async="true" to your index.html file.
In manifest.json file set a parameter async=true in rootView and routing.config
Now that the UI5 application is prepared for asynchronous loading of resources, we can register the service worker.
This process involves including a JavaScript file in the application that contains the service worker code and registering it with the browser.
During registration, the service worker script is downloaded and executed by the browser. Once registered, the service worker remains active in the background, ready to intercept network requests and perform caching operations.
One of the primary functions of service workers is to cache essential assets of a UI5 application, such as HTML files, CSS stylesheets, JavaScript files, and image resources. By caching these assets, the application can be loaded and accessed even when there is no internet connection.
The install event provides an opportunity for the service worker to perform necessary setup tasks, such as caching essential resources, in preparation for future offline functionality.
Caching assets with service workers involves intercepting network requests made by the application and storing the responses in the browser's cache. When a request is made for a cached asset, the service worker intercepts it and can respond to it with the cached version instead of sending a request to the server. This greatly improves the application's performance and reduces reliance on network connectivity.
Developers can define caching strategies based on their application's requirements. They can choose to cache assets only when the user explicitly requests to save them offline or implement automatic caching strategies to proactively cache frequently accessed resources.
There are several caching strategies you can implement in a service worker to control how resources are cached and served. Each strategy offers different benefits and is suited for specific use cases. Here is a list of common caching strategies:
This strategy bypasses the cache entirely and relies only on network requests to fetch resources.
- The service worker does not store or cache any responses.
This strategy bypasses the cache entirely and relies only on network requests to fetch resources.
- The service worker does not store or cache any responses.
- With the cache-only strategy, the service worker serves resources exclusively from the cache.
- If the requested resource is not found in the cache, the service worker responds with an error or a predefined offline page.
- With the cache-only strategy, the service worker serves resources exclusively from the cache.
- If the requested resource is not found in the cache, the service worker responds with an error or a predefined offline page.
- In this strategy, the service worker makes a network request first for a requested resource.
- If the network request is successful, the response is served to the client, and a copy is cached for subsequent use.
- If the network request fails or times out, the service worker retrieves the resource from the cache and serves it as a fallback.
- In this strategy, the service worker makes a network request first for a requested resource.
- If the network request is successful, the response is served to the client, and a copy is cached for subsequent use.
- If the network request fails or times out, the service worker retrieves the resource from the cache and serves it as a fallback.
- This strategy first checks the cache for a requested resource.
- If the resource is found in the cache, it is served to the client.
- If the resource is not in the cache, the service worker attempts to fetch it from the network and caches the response.
- If the network request fails or the resource is not available, a fallback response from a predefined cache is served.
- This strategy first checks the cache for a requested resource.
- If the resource is found in the cache, it is served to the client.
- If the resource is not in the cache, the service worker attempts to fetch it from the network and caches the response.
- If the network request fails or the resource is not available, a fallback response from a predefined cache is served.
- With this strategy, the service worker serves a cached response while simultaneously making a network request for an updated version of the resource.
- The cached response is immediately returned to the client, providing a fast initial load, and the updated response replaces the cached version once it is available.
- With this strategy, the service worker serves a cached response while simultaneously making a network request for an updated version of the resource.
- The cached response is immediately returned to the client, providing a fast initial load, and the updated response replaces the cached version once it is available.
While service workers can cache essential assets of a UI5 application, there may be scenarios where a requested resource is not yet cached. In such cases, it is important to handle offline requests gracefully.
One approach is to display a custom offline page or UI component that informs the user about the lack of network connectivity and provides alternative actions or content. This page can be designed to be visually consistent with the application's theme and branding.
Additionally, developers can implement strategies like displaying placeholder content, disabling certain features temporarily, or providing offline-friendly functionalities that don't rely heavily on server interactions. These approaches help to maintain a smooth user experience even when specific resources are not available offline.
After deploying a new version of service worker in which we removed some old assets and added some new ones in the list of assets to precache it’s important to clean out the outdated caches. That’s something you should do in the activate event.
When building offline-capable UI5 applications, it's important to have a reliable mechanism for storing and retrieving data locally. One popular choice for offline data storage is IndexedDB, a client-side database supported by modern browsers. IndexedDB provides a powerful and efficient solution for storing structured data, making it suitable for offline data storage in UI5 applications.
IndexedDB allows developers to create object stores to store and retrieve data. It supports indexing and querying, providing flexibility in data retrieval operations. By leveraging IndexedDB, UI5 applications can store user-specific data, cached API responses, or any other necessary data to ensure offline functionality.
Subheader a: Utilizing IndexedDB for offline data storage and retrieval
To use IndexedDB in conjunction with service workers, developers can employ the following steps:
Create an IndexedDB database: Define the structure of the database by specifying object stores and their respective indexes.
Open the database: In the service worker code, open the IndexedDB database using the appropriate version and object store configurations.
Store and retrieve data: Use the IndexedDB API to store data in object stores and retrieve it when needed. This can include storing offline form submissions, cached API responses, or other relevant data.
Synchronize data with server: When the network connection is available, UI5 applications can use the service worker to synchronize the locally stored data with the server, ensuring data consistency.
In addition to offline data storage, service workers offer background services that can enhance the functionality of UI5 applications. Two important background services to consider are Background Fetch and Background Sync. Let's explore how these services can be utilized for improved offline data management and synchronization.
Background Fetch allows UI5 applications to download large files or perform resource-intensive tasks in the background, even when the application is not actively open or the device is in a sleep state. This service is particularly useful for scenarios where users want to initiate a download or upload process and have it continue in the background, even if they navigate away from the application or their device goes into a low-power state. Service workers can handle Background Fetch events, perform the necessary network requests, and manage the progress and completion of the background tasks.
Background Sync enables UI5 applications to synchronize data with a server when a network connection becomes available, even if the application is not actively being used. It ensures that data changes made offline are automatically synced with the server, providing data consistency across devices. For example, when a user creates or updates data offline, the service worker can queue the data synchronization task, and when the network connection is restored, the service worker can automatically trigger the synchronization process. This ensures that data remains up-to-date without requiring manual intervention from the user.
Background Sync enables UI5 applications to synchronize data with a server when a network connection becomes available, even if the application is not actively being used. It ensures that data changes made offline are automatically synced with the server, providing data consistency across devices. For example, when a user creates or updates data offline, the service worker can queue the data synchronization task, and when the network connection is restored, the service worker can automatically trigger the synchronization process. This ensures that data remains up-to-date without requiring manual intervention from the user.
Background Sync enables UI5 applications to synchronize data with a server when a network connection becomes available, even if the application is not actively being used. It ensures that data changes made offline are automatically synced with the server, providing data consistency across devices. For example, when a user creates or updates data offline, the service worker can queue the data synchronization task, and when the network connection is restored, the service worker can automatically trigger the synchronization process. This ensures that data remains up-to-date without requiring manual intervention from the user.
Push notifications are a powerful feature that allows service workers to send real-time updates and alerts to users even when they are not actively browsing a website or using an application. Leveraging push notifications can greatly enhance the engagement and user experience of your UI5 application. In this section, we will explore how to implement and leverage push notifications using service workers.
To enable push notifications, you need to follow a series of steps. First, you need to request permission from the user to display notifications. This can be done using the `Notification.requestPermission()` method, which prompts the user to grant permission.
Once the user has granted permission, you can send notification from service worker to client. This involves calling the `self.registration.showNotification()` method.
Push notifications can include a title, body, icon, actions, and other options to provide rich and interactive content to the user.
After successfully implementing service worker there is only one more requirement to fulfill to turn our UI5 application into Progressive web application.
We need to add a web application manifest a JSON file that describes the PWA's metadata, such as its name, icons, theme color, and display mode. Include this file in the root directory of your application and reference it in your HTML using the <link rel="manifest" href="path/to/manifest.json"> tag.
After successfully implementing service worker there is only one more requirement to fulfill to turn our UI5 application into Progressive web application.
We need to add a web application manifest a JSON file that describes the PWA's metadata, such as its name, icons, theme color, and display mode. Include this file in the root directory of your application and reference it in your HTML using the <link rel="manifest" href="path/to/manifest.json"> tag.
After successfully implementing service worker there is only one more requirement to fulfill to turn our UI5 application into Progressive web application.
We need to add a web application manifest a JSON file that describes the PWA's metadata, such as its name, icons, theme color, and display mode. Include this file in the root directory of your application and reference it in your HTML using the <link rel="manifest" href="path/to/manifest.json"> tag.