This is continuation of the previous blog on making a website installable, you are highly encouraged to check it out before continuing.
What is deferred installation?
Installation Prompt, makes it easy for users to install a Progressive Web App (PWA) on their mobile or desktop device. Installing a PWA adds it to a user's launcher, allowing it to be run like any other installed app. Deferred installation allows the developer to display the installation prompt only when the user performs certain action, like clicking a button or hitting the bottom of the page (something to indicate that they are engaging with your site, makes it more likely that the user will install the PWA when prompted to do so).
Getting Started
We will be continuing from where we left off in the previous blog. But we require a small change in index.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"/><metahttp-equiv="X-UA-Compatible"content="IE=edge"/><metaname="viewport"content="width=device-width, initial-scale=1.0"/><title>PWA: Installable website</title></head><body><buttonid="btn">Click Me</button><!-- CHANGE: BUTTON ADDED --></body><script>if ('serviceWorker'innavigator){navigator.serviceWorker.register('/service-worker.js');}else{console.log("Service worker is not supported");}</script></html>
Setting up deferred installation
To set up deferred installation we need to add a script.
script.js
letdeferredPrompt;// Storing the installation promptwindow.addEventListener("beforeinstallprompt",(event)=>{deferredPrompt=event;});// Displaying the prompt on button clickconstbtn=document.getElementById('btn');btn.addEventListener("click",()=>{if (!deferredPrompt)returndeferredPrompt.prompt();});
Link the script in index.html.
<script src="script.js"></script>
Voila! That's all you need to defer the Installation Prompt.
NOTE: You can display the Installation Prompt only on user interaction like: click, scroll, form submit, etc.
Project using this Implementation
Smartsapp (deferred prompt on Google OAuth button click, login and registration )