Creating Progressive Web App WordPress

Category : WordPress

Progressive Web Apps are web apps that use emerging web browser APIs and features along with traditional progressive enhancement strategy to bring a native app-like user experience to cross-platform web applications. This guide will help you in Creating Progressive Web App WordPress and to solve any existing error related to Progressive Web app and improve it.

Requirements for creating Progressive Web App WordPress :

  • Domain with WordPress installed

Procedure for creating Progressive Web App WordPress :

Create Manifest :

It is a JSON file that controls how your app appears to the user and ensures that progressive web apps are discoverable. It describes the app’s name, the start URL, icons, and all of the other details necessary to transform the website into an app-like format.

  1. Create a new file named manifest.json in the root directory of your website.
  2. Create a folder named pwa_icons in the root directory of the website.
  3. Add the icons of your choice in the pwa_icons folder.
    Note: There should be at least two icons with the following dimensions.
    -> 192 x 192
    -> 512 x 512
  4. Open the manifest.json file with an editor. Add the following code to the file.
    {
    "name": "My Blog",
    "short_name": "My Blog",
    "description": "My WordPress Blog",
    "start_url": "https://yourdomain.com",
    "icons": [
    {
    "src": "/pwa_icons/logo.png",
    "sizes": "192x192",
    "type": "image/png",
    "purpose": "any maskable"
    },
    {
    "src": "/pwa_icons/logo-512x512.png",
    "sizes": "512x512",
    "type": "image/png"
    }
    ],
    "background_color": "#f8ea48",
    "theme_color": "#138e69",
    "display": "standalone",
    "orientation": "portrait",
    "scope": "/"
    }
    Note: Make changes to name, short_name, description, start_url, background_color and theme_color in the manifest.json file.
  5. Save the file.
  6. In your website’s root directory, open wp-content/themes here, choose the theme that is active on your website. After opening your active theme folder, find the functions.php file and open it with the editor.
  7. Add the following code to your functions.php file’s end.
    add_action( 'wp_head', 'inc_manifest_link' );
    function inc_manifest_link()  {
    echo '<link rel="manifest" href="/manifest.json">';
    }

    Save the file.
  8. The manifest.json file has been added to the website. It can be confirmed in the developer tools in Google Chrome, press F12 or Control + Shift + I,  click on the application tab, from the left menu select manifest it should display your manifest file as in the screenshot.
    manifest pwa

Adding Service worker :

  1. Create a new file javascript file named serviceworker.js in the root directory of the website.
  2. Open the file in edit mode, add the following code to the file.
    'use strict';
    const cacheName = 'yourdomain.com';
    const startPage = 'https://yourdomain.com';
    const offlinePage = 'https://yourdomain.com';
    const filesToCache = [startPage, offlinePage];
    const neverCacheUrls = [/\/wp-admin/,/\/wp-login/,/preview=true/];// Install
    self.addEventListener('install', function(e) {
    console.log('PWA service worker installation');
    e.waitUntil(
    caches.open(cacheName).then(function(cache) {
    console.log('PWA service worker caching dependencies');
    filesToCache.map(function(url) {
    return cache.add(url).catch(function (reason) {
    return console.log('PWA: ' + String(reason) + ' ' + url);
    });
    });
    })
    );
    });// Activate
    self.addEventListener('activate', function(e) {
    console.log('PWA service worker activation');
    e.waitUntil(
    caches.keys().then(function(keyList) {
    return Promise.all(keyList.map(function(key) {
    if ( key !== cacheName ) {
    console.log('PWA old cache removed', key);
    return caches.delete(key);
    }
    }));
    })
    );
    return self.clients.claim();
    });// Fetch
    self.addEventListener('fetch', function(e) {// Return if the current request url is in the never cache list
    if ( ! neverCacheUrls.every(checkNeverCacheList, e.request.url) ) {
    console.log( 'PWA: Current request is excluded from cache.' );
    return;
    }// Return if request url protocal isn't http or https
    if ( ! e.request.url.match(/^(http|https):\/\//i) )
    return;// Return if request url is from an external domain.
    if ( new URL(e.request.url).origin !== location.origin )
    return;// For POST requests, do not use the cache. Serve offline page if offline.
    if ( e.request.method !== 'GET' ) {
    e.respondWith(
    fetch(e.request).catch( function() {
    return caches.match(offlinePage);
    })
    );
    return;
    }// Revving strategy
    if ( e.request.mode === 'navigate' && navigator.onLine ) {
    e.respondWith(
    fetch(e.request).then(function(response) {
    return caches.open(cacheName).then(function(cache) {
    cache.put(e.request, response.clone());
    return response;
    });
    })
    );
    return;
    }e.respondWith(
    caches.match(e.request).then(function(response) {
    return response || fetch(e.request).then(function(response) {
    return caches.open(cacheName).then(function(cache) {
    cache.put(e.request, response.clone());
    return response;
    });
    });
    }).catch(function() {
    return caches.match(offlinePage);
    })
    );
    });// Check if current url is in the neverCacheUrls list
    function checkNeverCacheList(url) {
    if ( this.match(url) ) {
    return false;
    }
    return true;
    }
    Save the file.
  3. In your website’s root directory, open wp-content/themes here, choose the theme that is active on your website. After opening your active theme folder, find the functions.php file and open it with the editor.
  4. Add the following code to your functions.php file.
    function register_my_service_worker () {
    echo "<script>navigator.serviceWorker.register('/serviceworker.js')</script>";
    }
    add_action ( 'wp_head', 'register_my_service_worker' );
    Save the file.
  5. The serviceworker.js file has been added to the website. It can be confirmed in the developer tools in Google Chrome, press F12 or Control + Shift + I,  click on the application tab, from the left menu select Service Worker it should display your service worker file as in the screenshot.
    serviceworker pwa
  6. Now you can Check your Progressive Web app score from Lighthouse. In Google Chrome, press F12 or Control + Shift + I,  select the Lighthouse tab.
    lighthouse pwa
    Check the shown boxes in the Screenshot. Click the Generate Report button. Lighthouse will analyze the App and show results as follows.
    Creating Progressive Web App WordPress
    The result still has two missing components; to fix these errors, we have to make more changes to our files.

Additional Optimization:

Theme colour tag :

  1. In your website’s root directory, open wp-content/themes here, choose the theme that is active on your website. After opening your active theme folder, find the header.php file and open it with the editor.
  2. Add the following code in the file.
    <meta name="theme-color" content="#ff6600" />
    Note : #ff6600 can be replaced with the colour code of your website.
    Save the file.

Apple-touch-icon:

  1. In your website’s root directory, open wp-content/themes here, choose the theme that is active on your website. After opening your active theme folder, find the functions.php file and open it with the editor.
  2. Add the following code in the file.
    function bz__add_apple_touch_icons() {
    ?>
    <link rel="apple-touch-icon" href="<?php echo get_template_directory_uri(); ?>/pwa_icons/icon.png" />
    <link rel="apple-touch-icon" sizes="180x180" href="<?php echo get_template_directory_uri(); ?>/pwa_icons/icon.png" />
    <?php
    }
    add_action( 'wp_head', 'bz__add_apple_touch_icons' );
    Note: The path here (/pwa_icons/icon.png) leads to icon file with dimensions 192 x 192. Please adjust the path to the correct file.
    Save the file; test your website from Lighthouse as shown above. This time the result should be perfect.
    Creating Progressive Web App WordPress

We have various other useful guides for WordPress, which can be accessed by clicking here.