DEV Community

Cover image for Progressive Web Apps: The Future of Web Development
Baransel
Baransel

Posted on • Originally published at baransel.dev

Progressive Web Apps: The Future of Web Development

What's All This PWA Buzz About?

Picture this: You're on the subway, trying to check a website on your phone, but the signal keeps dropping. Frustrating, right? Enter Progressive Web Apps, the superheroes of the web world. They work offline, load at lightning speed, and even send you notifications. It's like giving your website superpowers!

The PWA Origin Story

Back in the day (like, way back in 2015), we had a choice: build a website or build an app. It was like choosing between a bicycle and a car. But then, some clever folks at Google thought, "Why not both?" And thus, the PWA was born!

Building Your First PWA: The Adventure Begins

Let's roll up our sleeves and build a simple PWA together. We'll create a "Dad Jokes" app because, well, who doesn't love a good (or bad) dad joke?

Step 1: The Basics - Just a Regular Webpage

First, let's create a basic HTML file. This is our "bicycle" - functional, but not quite super-powered yet.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dad Jokes PWA</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Dad Jokes</h1>
    <p id="joke">Click the button for a dad joke!</p>
    <button id="jokeBtn">Get New Joke</button>
    <script src="app.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 2: Add Some Style - Because Even Dad Jokes Need to Look Good

Let's add a touch of CSS to make our app look snazzy:

body {
    font-family: Arial, sans-serif;
    text-align: center;
    padding: 20px;
}

#joke {
    margin: 20px 0;
    font-style: italic;
}

button {
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
}
Enter fullscreen mode Exit fullscreen mode

Step 3: The Magic of JavaScript - Fetching Dad Jokes

Now, let's add some JavaScript to fetch jokes from an API:

const jokeElement = document.getElementById('joke');
const jokeBtn = document.getElementById('jokeBtn');

async function fetchJoke() {
    try {
        const response = await fetch('https://icanhazdadjoke.com/', {
            headers: {
                'Accept': 'application/json'
            }
        });
        const data = await response.json();
        jokeElement.textContent = data.joke;
    } catch (error) {
        jokeElement.textContent = "Oops! Looks like the joke got stuck in dad's old briefcase.";
    }
}

jokeBtn.addEventListener('click', fetchJoke);

// Fetch a joke when the page loads
fetchJoke();
Enter fullscreen mode Exit fullscreen mode

Step 4: The PWA Transformation - Adding Superpowers

Now, let's turn our regular website into a PWA. First, we need a manifest file. Create a file named manifest.json:

{
    "name": "Dad Jokes PWA",
    "short_name": "DadJokes",
    "start_url": "/",
    "display": "standalone",
    "background_color": "#ffffff",
    "theme_color": "#4285f4",
    "icons": [
        {
            "src": "icon.png",
            "sizes": "192x192",
            "type": "image/png"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

Don't forget to add a link to this manifest in your HTML:

<link rel="manifest" href="manifest.json">
Enter fullscreen mode Exit fullscreen mode

Step 5: The Secret Sauce - Service Workers

Service workers are like tiny, invisible web butlers. They cache your assets and even work offline. Create a file named service-worker.js:

const CACHE_NAME = 'dad-jokes-cache-v1';
const urlsToCache = [
    '/',
    '/index.html',
    '/style.css',
    '/app.js',
    '/icon.png'
];

self.addEventListener('install', event => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then(cache => cache.addAll(urlsToCache))
    );
});

self.addEventListener('fetch', event => {
    event.respondWith(
        caches.match(event.request)
            .then(response => response || fetch(event.request))
    );
});
Enter fullscreen mode Exit fullscreen mode

Now, register this service worker in your app.js file

if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker.register('/service-worker.js')
            .then(registration => console.log('ServiceWorker registered'))
            .catch(error => console.log('ServiceWorker registration failed:', error));
    });
}
Enter fullscreen mode Exit fullscreen mode

Testing Your PWA Superpowers

  1. Offline Mode: Turn off your internet and refresh the page. Your app should still work!
  2. Install Prompt: On supported browsers, you should see an option to install your PWA.
  3. Lighthouse Audit: Use Chrome's Lighthouse tool to check your PWA's superpowers.

The Future is Progressive

Congratulations! You've just built your first PWA. It's like watching your child take their first steps, isn't it? (Speaking of dad jokes...)

As we move further into 2024, PWAs are becoming more powerful. They can access device features, work offline, and provide an app-like experience without the hassle of app stores.

So, the next time someone asks if you can build them a website or an app, you can say, "Why not both?" and introduce them to the wonderful world of PWAs!

What do you think about PWAs? Have you built one before? Let me know in the comments below, and don't forget to share your favorite dad jokes!

Top comments (3)

Collapse
 
armando_ota_c7226077d1236 profile image
Armando Ota • Edited

this is local .. the fun starts when you start using it for phones ... all the bridges and plugins to test .. because some work some don't.
I love PWA ...but be careful when making it for the phones:

  • animations (are slugish)
  • decide on which bridge you want to use (cordova or ...)
  • try a lot of plugins before you decide on the one you will integrate it in your app (for example: you need notifications and badges etc... )

It's all fun and games up to the moment it's not ;)

Collapse
 
gads_hfd_f9760262ae41dc11 profile image
Gads Hfd

Absolutely loved this post! 🎉 It’s fantastic to see the exciting future of Progressive Web Apps (PWAs) being highlighted. They truly are a game-changer with their ability to blend the best of both web and native app experiences. The analogy of a child's first steps was spot on—building a PWA feels like a proud achievement!

I agree that PWAs are incredibly powerful, offering offline capabilities and seamless access to device features without the need for app stores. It's great to see how they’re evolving and becoming more integral in the tech landscape.

And yes, “Why not both?” is the perfect response when asked about building a website or an app. PWAs are the best of both worlds!

I’ve had the chance to build a few PWAs myself, and it’s been an exciting journey. Can’t wait to see more innovations in this space. Also, here’s a dad joke to add to the fun: Why don’t skeletons fight each other? They don’t have the guts! 😄

Looking forward to more insightful posts like this!

Collapse
 
coder_one profile image
Martin Emsky

As long as the existence of the PWA is boycotted at every turn by Apple, it has no chance of becoming widespread.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.