What is PWA: Comprehensive Guide with Code Samples - Picture №1
01

What is PWA: Comprehensive Guide with Code Samples

Content:
Rate this article
Thank you for feedback!
5.0
1138 Views

Progressive Web Apps are web applications that bring best web and mobile features. PWAs are similar to native apps in functionality and can be used on any device with a web browser. When it comes to mobile devices, PWAs are fully supported on Android and, albeit with certain limitations, on iOS.


The power of PWAs has already been experienced by major players like Twitter, Forbes, and Pinterest, which has resulted in significant user improvements and advertising revenue. Quite understandable, given that PWA apps provide a new, native-app-like experience and are relatively cost-effective to implement. Receiving push notifications, seamless offline working, and quick access without downloading are all possible with PWAs. This marks a new 'progressive' era in website development, prioritising versatility.


Let's take a closer look at progressive web applications. In order to assist you in comprehending this process, we have developed an illustrative guide with code samples for PWA.


Pros: seamless user experience

Developers and users are drawn to PWAs due to their main advantages:

  • Cross-platform compatibility. PWAs are compatible with devices running different operating systems, screen sizes, and browsers such as Chrome, Firefox, Safari, and Edge. The single universal application significantly reduces development costs.
  • Offline mode. PWA can fully function without the Internet or unstable connections due to resource caching provided by service workers technology. Push notifications continue to be received even when the browser is closed.
  • The desktop installation. Users can add a PWA icon to their device's screen, and the application will function natively.
  • Publication in app stores. PWA applications can be published in stores such as Google Play Store, Microsoft Store, and Meta Quest Store using the PWABuilder tool.
  • Background updating. The developers automatically provide bug fixes for PWA applications, so they don't need to regularly install new versions from the app store. Furthermore, PWA can be used through the browser without requiring complicated installation.
  • Cost-effectiveness. Unlike native applications, PWAs can be fast on low-end phones because its considerably use less memory on devices. Additionally, caching resources significantly reduces network load.
  • Performance. PWAs are easily thanks to loading and responding to user actions instantly.
  • URL links. PWAs can be effortlessly shared via a standard browser link, a capability not available with other types of applications.
  • Data access. PWAs are located on the server, therefore, easy access to data is available on all platforms.

These advantages allow PWA applications to effectively mimic the UI/UX of native applications and even outdo its in many ways.


The main advantages of PWA (Progressive Web App) applications - image


Cons: limitations and hurdles

PWAs have downsides in specific areas:

  • iOS limitations. The functionality of PWA on Apple devices is limited due to a lack of support for service workers and certain individual PWA functions.
  • Device access issues: PWAs with specific functionality or high performance often encounter limited support for low-level APIs. These APIs provide access to the device's hardware, including memory operations, input-output, and network protocols. Unlike native apps, PWAs often request additional device access and may not always fully support it.
  • Browser restrictions: PWAs are web applications, operating within the confines of the browser. Their functionality may be limited by browser security settings.

PWA applications have some drawbacks, but most are related to platform limitations.


Regarding development, PWA is rich in styles and possibilities for combining them, markup flexibility, and use of scripting languages. Thanks to this, developers can make the most interactive controls possible by balancing the pros and cons mentioned above. The choice of tools depends on future users' needs and the application's functional requirements.


Let's dive into the standard PWA development process to see how a website can look like an app, have a corporate icon on the screen, and be almost independent of an internet connection.


PWA development process

The development of Progressive Web Apps is quite similar to the creation of native applications regarding approaches. For PWA, the browser is the virtual machine. To ensure that a PWA application runs smoothly offline, the following tools are used:

  • Service workers for caching resources such as HTML pages, images, JavaScript files, and styles.
  • IndexedDB for storing structured data such as text, images, and settings, even in large volumes.
  • LocalStorage for storing small amounts of data as a key-value without a time limit.
  • SessionStorage for storing limited data available only after one browser session.
  • JSON and API for downloading and saving data and exchanging it with the server via JavaScript.

The success of the offline operation and data synchronisation when returning to online mode is ensured by proper planning and the correct development approaches.


Web App Manifest

Let's get started on the Web App Manifest. This JSON file is responsible for displaying PWA as a native app with an icon. The application's metadata, including the author, icon, colours, name, and configuration options, like navigation methods or screen deployment, are transmitted to the device through the Manifest. This file is used to determine the correct display of the application and its integration with the device.


What is a service worker and how does it work?

Service workers play a significant role in the work of PWA - special JavaScript scripts that the browser allows you to use. Service workers capable of working in the background and have their own lifecycle. To ensure proper functioning, service workers must be registered and installed in a JavaScript file that is connected to an HTML page.


Service workers cache data using network requests if the user's device is connected to the internet, and the application that has already been updated works both online and offline. The lack of involvement by the user in this process provides numerous advantages for seamless interaction with the application and version stability.


Despite the application being closed, service workers scripts still send push notifications. Notifying them of any important events or updates is possible with this method.


Lifecycle of service workers in a PWA

  1. Registration. The process begins by registering the service worker on the application page using navigator.serviceWorker.register() method. At the time, the service worker runs in the background.
  2. Installation. Service workers have been installed in the browser and the resources required for the PWA action have been downloaded and cached at this moment.
  3. Activation. If the installation goes well, service workers will be activated. Clearing outdated cached resources can be accomplished during this process.
  4. Managing requests. Activated service workers in PWAs intercept network requests and handle them.
  5. Updates. Simply modifying the source code or registering and activating a new version of the service worker is sufficient for this.
  6. Shutdown. For the sake of saving browser resources, service worker can be disabled or suspended if they are irrelevant. This happens when the application itself closes, and when the browser optimises its work and stops some of the scripts for the sake of performance.

Today, service workers are pivotal in PWA development, governing programmatic caching. Service workers scripts are expected to have even more capabilities and expand the scope of advanced web applications in the near future.


Installing PWA

The PWA installation banner informs users that Progressive Web Apps can be installed on their gadgets. It looks like a pop-up message, a special button on the website, or a widget with the ‘Add to Home’ or ‘Install’ option. Users will be able to quickly launch the application and remember about it thanks to the installed icon.


PWA owners have additional benefits such as a significant increase in user engagement and activity, as well as their focus on the application and brand as a whole. Installing an app on a device is a vital strategy for promoting PWAs, and it is crucial to make the process as simple as possible for end users.


Let's take a look at the basics of creating an installation banner:

  1. Add a meta tag to the HTML page that indicates that it is a PWA.
  2. Set up the installation banner in the JSON manifest by giving it a name, app icon, or favicon.
  3. Insert the JavaScript code into the PWA to display the ‘Install’ banner when the website is visited.

    What is PWA: Comprehensive Guide with Code Samples - Picture №5

Upon clicking on the banner, the user will see the application icon appear on their device's desktop.


Support page

The offline support page is another significant component of PWA. Typically, this is a simplified version of the application's content, the primary objective of which is to provide valuable information to the user even when they are offline. Thanks to caching, all the necessary resources are downloaded and stored on the device during the initial visit to a progressive website.


This is the way a support page is created:

  • Creating an HTML page that contains the necessary information to indicate that the application is offline.
  • Saving this page as a static resource in the cache using caches.open() and caches.addAll() methods.

    What is PWA: Comprehensive Guide with Code Samples - Picture №6

  • In order to ensure that the necessary resource is in the cache during the 'fetch' event, which is also known as 'request' or 'receive', service worker can be used.

    What is PWA: Comprehensive Guide with Code Samples - Picture №7

During the ‘fetch’ event, which signifies a request or retrieval, service workers can check if the required resource is available in the cache. If it's not there, and there's currently no internet connection, a support page for offline mode needs to be provided in response.


Caching strategies and concepts in PWA

Caching is essential for ensuring performance and availability in modern PWA applications. Caching allows resources to be stored on the client's device and reduces dependence on the internet network.


When the device is offline, service workers use the cached dynamic and static data, such as HTML, CSS, JavaScript, images, fonts, and more.


Setting up caching in a PWA

Setting up caching in a PWA application occurs precisely during the installation phase of the service workers lifecycle. This is when essential resources for the application are stored, ensuring their availability in offline mode or during low internet connections.


A portion of the service workers script, typically the ‘Install’ event handler, looks like this:


What is PWA: Comprehensive Guide with Code Samples - Picture №8


The code for caching resources for PWA is located in the event.waitUntil function. With this function, the browser ‘waits’ for certain asynchronous operations in the application to complete and then proceed to the next stage.


Cache removal and updating in a PWA application

As soon as the new version of service workers has been successfully installed and activated, the ‘activate’ event occurs. Its main purpose is to prepare the application for this version of service workers. During this event, the following actions are executed:

  1. Keeping the cache clean. Clearing outdated cached resources from service workers and freeing up space.
  2. Installing a new cache. Place a new cache on a free space to store new resources or update the existing one.
  3. Other useful actions to activate the updated version of service workers in PWA.

Here is a sample code to handle the ‘activate’ event:


What is PWA: Comprehensive Guide with Code Samples - Picture №9


Cache and network operation control in PWA

The next event in service workers is called ‘fetch’. Its purpose is to intercept a network request when a page is loaded and respond to it independently, while controlling caching and network operations.


PWA's cache is a temporary environment where users store copies of web pages, scripts, images, and other resources that they have already downloaded. The secret behind progressive web applications is the ability to utilise storage instead of downloading all the data again every time you interact with them.


The code for handling this event usually looks like this:


What is PWA: Comprehensive Guide with Code Samples - Picture №10


Various concepts and strategies for caching and data management can be implemented using the 'fetch' event in service worker, and sometimes they can even be combined.


Strategies: precaching and dynamic caching


Preliminary and dynamic caching is the most common method for ensuring the smooth operation of PWA offline.


Precaching

Precaching assets in a PWA application, or Pre-Caching Assets, means saving all static resources when service workers are installed or activated.


The next steps are easy to follow:

  1. Define a checklist of essential resources for pre-caching, consisting of JavaScript, CSS, fonts, and the HTML page. For example:

    What is PWA: Comprehensive Guide with Code Samples - Picture №11

  2. Create a cache to which the stored resources are added using the caches.open() method.
  3. Provide access to the cache so that service workers can use this data during the ‘fetch’ event.
  4. Update the cache when a service worker is activated or the application changes.

Pre-caching in PWA allows for resource storage in advance, which ensures optimal first page load speed, especially when loading large pages.


Dynamic caching

PWA uses dynamic caching to cache resources in real-time, based on current network requests. By using this strategy, the cache can be managed more flexibly by responding to user actions or content changes.


Dynamic caching is implemented in the following steps:

  • The ‘fetch’ event in the service worker:

    What is PWA: Comprehensive Guide with Code Samples - Picture №12

  • Checking the cache. To check the cache response during a network request, use the caches.match(event.request) method:

    What is PWA: Comprehensive Guide with Code Samples - Picture №13

  • Refreshing the cache. This resource's cache can be updated depending on the response:

    What is PWA: Comprehensive Guide with Code Samples - Picture №14

The value of dynamic caching in PWA lies in its ability to update data on the fly, in real-time, and only store data that is relevant to the user. The server's load is greatly reduced while the application is running.


In general, the caching logic, strategy choices, and combinations are determined by the PWA application's requirements.


Caching concepts: conditional fallbacks


Conditional Fallbacks in PWA is the main concept of caching and maintaining backup versions of content. It provides flexible solutions for offline mode and allows you to dynamically adapt the application's content depending on different conditions.


Conditional fallbacks are implemented in the following way:

  • Define the conditions under which backup resources should be changed: geolocation, device type, screen size, Internet connection, etc.
  • In PWA, you can create backup resources by creating pages with different versions for different conditions and types of devices.
  • The 'fetch' event handler's optional code will allow for flexible selection of the required fallback resource for current conditions:

    What is PWA: Comprehensive Guide with Code Samples - Picture №15

The backup resources themselves, which are defined in the ‘fetch’ handler, are cached in the ‘Install’ handler or other places in the code if necessary.


Thanks to Conditional Fallbacks, the PWA content is flexible and adapts to the conditions and needs of the user, which ensures a flawless user experience.


Limiting cache size in PWAs


Limiting the cache is another step in PWA development. The cache must not take up too much space on the user's device, otherwise it will negatively impact performance. The following approaches are utilised to achieve this objective:

  • Setting up a maximum cache size, regularly checking it, and updating it. This can be achieved by using JavaScript, service workers, and special libraries for working with the cache.
  • Use special methods in service workers, delete outdated cache in the application.
  • Keep important data in the PWA through selective caching.
  • Use a system that tracks resource consumption and automatically removes unneeded resources from the cache.
  • Use version control to eliminate any outdated resources to update the application by the user.

Deleting the cache may look like this:


What is PWA: Comprehensive Guide with Code Samples - Picture №16


Proper management of cache size, based on application requirements and device type, will maintain optimal PWA performance.


Local database management: IndexedDB and LocalStorage

To ensure accurate data storage on the user's device while the PWA application is offline, LocalStorage and IndexedDB are used. The browser's databases allow for the storage and access of structured data.


LocalStorage is suitable for storing small amounts of data in the form of a string-string or key-value. This database has a limit on the amount of data and a fast but simple API that aids in storing, retrieving, and deleting data by key. In case the data is expected to exceed 10 MB, more powerful mechanisms are required, and in this case, IndexedDB is added.


IndexedDB handles data that is more complex and offers an extensive API for complex queries and index creation to provide quick access to data.


Let's consider the stages of working with IndexedDB:

  • Creating an IndexedDB database using JavaScript:

    What is PWA: Comprehensive Guide with Code Samples - Picture №17

  • Constructing an Object Store as a storage container for data:

    What is PWA: Comprehensive Guide with Code Samples - Picture №18

  • Adding and retrieving data from the Object Store:

    What is PWA: Comprehensive Guide with Code Samples - Picture №19

  • Updating and deleting data from the Object Store.
  • Establishing and terminating connections and transactions with the Object Store.

IndexedDB is accessible to most modern web browsers and is adapted for PWA development.


Verifying PWA functionality

To check the performance of PWAs, Google's Lighthouse tool is used. It assesses the effectiveness of various components of the application, such as performance, accessibility, page load, and so on.

  • availability and correctness of service workers;
  • caching of static and dynamic content and compliance of this process with the best PWA practices;
  • indexing of pages in the search engine;
  • availability of the manifest file and its content;
  • progressiveness, which is the ability of the application to operate on different screens and offline;
  • page loading performance while simultaneously seeking ways to improve it;
  • accessibility, privacy, etc.

A detailed report will be provided by Lighthouse with recommendations to improve PWA's performance after its audit.


Updating UI in PWAs

The user interface in PWA applications is usually updated in real time. When users open the app or refresh the page, they are automatically given access to the new version. They can observe changes in design, text, animation, optimised loading speed, and new features.


In PWA development, UI updates are implemented using the following tools:

  • JavaScript allows access to DOM elements, change their properties, and change their content.

    What is PWA: Comprehensive Guide with Code Samples - Picture №20

  • Through AJAX requests, such as Fetch API or XMLHttpRequest, you have access to receive or send data to the server and update the UI based on it.
  • Frameworks and libraries provide tools for declarative UI updates when data changes.
  • WebSockets and Server-Sent Events technologies allow you to establish an uninterrupted connection to the server to instantly update the application UI.
  • Push notifications via service workers notify users of updates even when the PWA is inactive.

In this article, we've thoroughly explored all key aspects of PWA development and the capabilities of these applications. PWAs are revolutionising the web space, combining the best features of websites and native apps into one innovative solution. Today, they offer flawless UI/UX experiences for users, boundless opportunities for developers, and promising prospects for the future.

Next article What is a Single Page Application?
Previous article Why is a CRM System Needed: Concept, Advantages, and Varieties
Let's discuss your project
By clicking the ‘Send’ button, you consent to the processing of personal data. Learn more.
Blog
#0000

Read more articles in our blog

Our experience: catering and food delivery
22 Feb, 2022
In the field of public catering, especially when a company is popular, the systematization of orders and proposals for customers plays a crucial role.
VIEW ARTICLE
What is PWA: Comprehensive Guide with Code Samples - Picture №21
YII vs Laravel: What is the Best Option for Your Project?
02 Jan, 2024
Thanks to technological development, it is no longer necessary to write PHP code from scratch: there are many frameworks — ready-made models, "templates" for software platforms, among which Yii2 and Laravel became the most popular. In what their difference and which of the frameworks to choose for creating a product? We tell and compare the structures in this material.
VIEW ARTICLE
What is PWA: Comprehensive Guide with Code Samples - Picture №22
Why is a CRM System Needed: Concept, Advantages, and Varieties
22 Feb, 2024
CRM is software for automating and managing customer interactions. Here, all data about the history of orders and sales, about each customer and his preferences, as well as about previous interactions of the brand with the consumer, are stored electronically.
VIEW ARTICLE
Understanding Cross-Browser Layout: What Does It Mean?
25 Jul, 2023
Cross-browser layout is a method of creating web pages that ensures the correct and identical display of the site in different browsers and their versions.
VIEW ARTICLE
 
Contacts
#0000

Ready to get started?
Reach out to us!

Address:

Ukraine, Zhytomyr
Vitruka Street, 9V

Shedule:

Mon–Fri, 9 am–7 pm

Address:

Poland, Warsaw, 00-842
Łucka Street 15/204

Shedule:

Mon–Fri, 9 am–7 pm

 
 
Contact us
#0000

Got a question?

Please fill out the form below, and our specialists will contact you as soon as possible!
By clicking the ‘Send’ button, you agree to the processing of personal data. Click to learn more.