DEV Community

Cover image for Convert Svelte to PWA.
Alish Giri
Alish Giri

Posted on

1 1

Convert Svelte to PWA.

Step 1

Create a folder called service-worker inside src/ folder.

Step 2

Create a new file called index.ts or index.js inside src/service-worker/ folder with the following contents.

/// <reference types="@sveltejs/kit" />

import { build, files, version } from '$service-worker';

const CACHE = `cache-${version}`;

const ASSETS = [
    ...build, // the app itself
    ...files // everything in `static`
];

self.addEventListener('install', (event) => {
    // Create a new cache and add all files to it
    async function addFilesToCache() {
        const cache = await caches.open(CACHE);
        await cache.addAll(ASSETS);
    }
    event.waitUntil(addFilesToCache());
});

self.addEventListener('activate', (event) => {
    // Remove previous cached data from disk
    async function deleteOldCaches() {
        for (const key of await caches.keys()) {
            if (key !== CACHE) await caches.delete(key);
        }
    }
    event.waitUntil(deleteOldCaches());
});

self.addEventListener('fetch', (event) => {
    // ignore POST  requests, etc
    if (event.request.method !== 'GET') return;

    async function respond() {
        const url = new URL(event.request.url);
        const cache = await caches.open(CACHE);

        // `build`/`files` can always be served from the cache
        if (ASSETS.includes(url.pathname)) {
            return cache.match(url.pathname);
        }

        // for everything else, try the network first, but
        // fall back to the cache if we're offline
        try {
            const response = await fetch(event.request);

            if (response.status === 200) {
                cache.put(event.request, response.clone());
            }

            return response;
        } catch {
            return cache.match(event.request);
        }
    }

    event.respondWith(respond());
});

Enter fullscreen mode Exit fullscreen mode

Step 3

Create manifest.json file inside static/ folder with the following contents.

Logos and screenshots should be placed inside static/ folder. For this tutorial I have used static/pwa-assets/ folder.

{
    "name": "app_name",
    "description": "app_description",
    "display": "standalone",
    "start_url": "/",
    "orientation": "portrait-primary",
    "prefer_related_applications": false,
    "icons": [
        {
            "src": "pwa-assets/logo-144.png",
            "sizes": "144x144",
            "type": "image/png"
        },
        {
            "src": "pwa-assets/logo-512.png",
            "sizes": "512x512",
            "type": "image/png",
            "purpose": "maskable"
        }
    ],
    "screenshots": [
        {
            "src": "pwa-assets/app-screenshot.png",
            "sizes": "1280x720",
            "type": "image/png",
            "form_factor": "wide",
            "label": "screenshot_description_here"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

Step 4

Add the following to the head tag on the src/app.html file.

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

Enjoy your Svelte Progressive Web App (PWA)! 🫡

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (3)

Collapse
 
kvetoslavnovak profile image
kvetoslavnovak

Thank you. Does it work for Sveltekit apps as well?

Collapse
 
wootcot profile image
Alish Giri

Yeah, if it a web based platform then it will work.

Collapse
 
kvetoslavnovak profile image
kvetoslavnovak

Yeah, works great, thank you.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay