A progressive web application (PWA) is a type of application software delivered through the web, built using common web technologies including HTML, CSS and JavaScript. It is intended to work on any platform that uses a standards-compliant browser, including both desktop and mobile devices. Since a progressive web app is a type of webpage or website known as a web application, they do not require separate bundling or distribution. There is no requirement for developers or users to install the web apps via digital distribution systems.
Here are the steps for converting your website into a PWA.
1. Manifest registration
Before installing the PWA, the browser should check if the manifest file already exists. You can use either of these ways to register a service worker.
a. Plugin
Install a script plugin and add this code.
<link rel="manifest" href="/manifest.json">
b. Theme file editor
Before using this method, ensure that you maintain a complete documentation and backup of your WordPress website.
- Navigate to WP Admin > Appearance > Theme File Editor.
- Select functions.php.
- Insert the following code at the last line in the functions.php.
//manifest file
add_action( 'wp_head', 'inc_manifest_link' );
// Creates the link tag
function inc_manifest_link() {
echo '<link rel="manifest" href="/manifest.json">';
}
2. Manifest file
The web app manifest is a W3C specification defining a JSON-based manifest (usually labelled manifest.json) to provide developers a centralized place to put metadata associated with a web application including:
- The name of the web application.
- Links to the web app icons or image objects.
- The preferred URL to launch or open the web app.
- The web app configuration data.
- Default orientation of the web app.
- The option to set the display mode, e.g., full screen.
This metadata is crucial for an app to be added to a home screen or otherwise listed alongside native apps. Create a new file called manifest.json in the root of your site. The file should entail the following.
{
"name": can be used by app stores or browsers on startup screens and prompts.
"short-name": used to display the name to the user within the icon. For example: in the homescreen.
"description": provides additional context about the app.
"dir": Direction of the text.
Values: ltr(left to right),
rtl (right to left),
auto
"lang": Language of the text.
Example: en (English)
"icons": Array of icons that the browser can choose from, including size and type.
[{
"src": source,
"sizes": i.e. "192x192",
"type": i.e. "image/png",
"purpose": the purpose of the image in the context of the host OS.
Values: badge, maskable, any
}]
"display": Preferred display mode for the website.
Values: fullscreen,
standalone,
minimal-ui,
browser.
"scope": it represents the set of urls that can be viewed through the installable web context, if the user navigates outside this scope, those pages will be opened in a standard browser.
Example:"https://example.com/", "/app/"
"orientation": you can enforce the orientation of your app, it can be ommited.
Example: natural (default).
"background_color": tells the browser what color to use on the startup splash screen that users will see when they launch your app.
Example: "#456BD9"
"theme_color": is used by some browsers to tint the status bar, address bar, and other parts of the browser user interface.
"start_url": indicates what page should launch when someone opens your progressive web app.
"categories": This is intended to be used by app stores to categorize your app.
Example: ["business", "technology", "web"]
}
3. Service worker registration
Each service worker must be registered in the client’s browser. Service workers go through a three-step lifecycle of registration, installation and activation. Registration involves telling the browser the location of the service worker in preparation for installation. As with any other JavaScript, you load the service-worker.js script in your HTML. Once running, it will open its own instance, so there will be no access to distributed object model elements.
You can use either of these ways to register a service worker.
a. Plugin
Install a script plugin and add this code.
<script src='/service-worker-register.js'></script>
b. Theme file editor
Before using this method, ensure that you maintain a complete documentation and backup of your WordPress website.
- Navigate to WP Admin > Appearance > Theme File Editor.
- Select functions.php.
- Insert the following code at the last line in the functions.php.
//service worker registration
function register_my_service_worker () {
echo "<script>navigator.serviceWorker.register('/service-worker.js')</script>";
}
add_action ( 'wp_head', 'register_my_service_worker' );
c. index.xml
Add the following code to your index.xml file.
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js', {
scope: './'
}).then(function (registration) {
var serviceWorker;
if (registration.installing) {
serviceWorker = registration.installing;
document.querySelector('#kind').textContent = 'installing';
} else if (registration.waiting) {
serviceWorker = registration.waiting;
document.querySelector('#kind').textContent = 'waiting';
} else if (registration.active) {
serviceWorker = registration.active;
document.querySelector('#kind').textContent = 'active';
}
if (serviceWorker) {
// logState(serviceWorker.state);
serviceWorker.addEventListener('statechange', function (e) {
// logState(e.target.state);
});
}
}).catch (function (error) {
// Something went wrong during registration. The service-worker.js file
// might be unavailable or contain a syntax error.
});
} else {
// The current browser doesn't support service workers.
// Perhaps it is too old or we are not in a Secure Context.
}
4. Service worker file
A service worker is a web worker that implements a programmable network proxy that can respond to web/HTTP requests of the main document. It is able to check the availability of a remote server and to cache content when that server is available, and serve that content later to the document. Service workers go through a three-step lifecycle of registration, installation and activation. After registration, installation and activation cycles follow.
Installation occurs when there is no service worker installed in the browser for the webapp, or if there is an update to the service worker. Activation occurs when all of the PWAs pages are closed, so that there is no conflict between the previous version and the updated one. The lifecycle also helps maintain consistency when switching among versions of service worker since only a single service worker can be active for a domain.
Create a new file called “service-worker.js” in the root of your site and add the code below.
var CACHE_NAME = 'cache-v1';
var urlsToCache = [
'/'
];
self.addEventListener('install', function(event) {
// Perform install steps
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
self.addEventListener('activate', function(event) {
var cacheWhitelist = ['cache-v1'];
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});