---
title: "Minimal offline-ready Service Worker example"  
description: "Minimal offline-ready Service Worker example"  
author: "ICSM Computer"  
published: 2025-08-12  
updated: 2025-08-12  
canonical: https://www.mindstick.com/interview/34351/minimal-offline-ready-service-worker-example  
category: "services"  
tags: ["javascript"]  
reading_time: 3 minutes  

---

# Minimal offline-ready Service Worker example

## 1. Project Structure

```plaintext
/index.html
/app.js
/service-worker.js
```

## 2. index.html

A basic page with a linked JS file to register the [service worker](https://www.mindstick.com/interview/34347/how-to-enable-etag-support-for-static-content-css-js-images-etc).

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Service Worker Demo</title>
</head>
<body>
    <h1>Hello Service Worker</h1>
    <p>Turn off your internet after first load and refresh to see it work offline.</p>

    <script src="app.js"></script>
</body>
</html>
```

## 3. app.js (Registers the service worker)

```javascript
if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker
            .register('/service-worker.js')
            .then(reg => {
                console.log('Service Worker registered with scope:', reg.scope);
            })
            .catch(err => {
                console.error('Service Worker registration failed:', err);
            });
    });
}
```

## 4. service-worker.js (Caches files for offline use)

```javascript
const CACHE_NAME = 'demo-cache-v1';
const ASSETS_TO_CACHE = [
    '/',            // Root
    '/index.html',
    '/app.js'
];

// Install event - cache the files
self.addEventListener('install', event => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then(cache => {
                console.log('Caching assets...');
                return cache.addAll(ASSETS_TO_CACHE);
            })
    );
});

// Activate event - clean old caches
self.addEventListener('activate', event => {
    event.waitUntil(
        caches.keys().then(keys => {
            return Promise.all(
                keys.map(key => {
                    if (key !== CACHE_NAME) {
                        console.log('Deleting old cache:', key);
                        return caches.delete(key);
                    }
                })
            );
        })
    );
});

// Fetch event - serve from cache, fallback to network
self.addEventListener('fetch', event => {
    event.respondWith(
        caches.match(event.request)
            .then(response => response || fetch(event.request))
    );
});
```

## 5. How to Test

1. [Serve files locally](https://www.mindstick.com/interview/34348/what-is-a-service-worker-and-how-does-it-differ-from-a-traditional-javascript-script) using HTTPS or `localhost` (e.g., with `npx http-server` or Live Server in VS Code).
2. Open the site in Chrome.
3. Check **DevTools → Application → Service Workers** — you should see it active.
4. Load once, then go **offline** and refresh — the cached files will still load.

## Answers

### Answer by ICSM Computer

## 1. Project Structure

```plaintext
/index.html
/app.js
/service-worker.js
```

## 2. index.html

A basic page with a linked JS file to register the [service worker](https://www.mindstick.com/interview/34347/how-to-enable-etag-support-for-static-content-css-js-images-etc).

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Service Worker Demo</title>
</head>
<body>
    <h1>Hello Service Worker</h1>
    <p>Turn off your internet after first load and refresh to see it work offline.</p>

    <script src="app.js"></script>
</body>
</html>
```

## 3. app.js (Registers the service worker)

```javascript
if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker
            .register('/service-worker.js')
            .then(reg => {
                console.log('Service Worker registered with scope:', reg.scope);
            })
            .catch(err => {
                console.error('Service Worker registration failed:', err);
            });
    });
}
```

## 4. service-worker.js (Caches files for offline use)

```javascript
const CACHE_NAME = 'demo-cache-v1';
const ASSETS_TO_CACHE = [
    '/',            // Root
    '/index.html',
    '/app.js'
];

// Install event - cache the files
self.addEventListener('install', event => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then(cache => {
                console.log('Caching assets...');
                return cache.addAll(ASSETS_TO_CACHE);
            })
    );
});

// Activate event - clean old caches
self.addEventListener('activate', event => {
    event.waitUntil(
        caches.keys().then(keys => {
            return Promise.all(
                keys.map(key => {
                    if (key !== CACHE_NAME) {
                        console.log('Deleting old cache:', key);
                        return caches.delete(key);
                    }
                })
            );
        })
    );
});

// Fetch event - serve from cache, fallback to network
self.addEventListener('fetch', event => {
    event.respondWith(
        caches.match(event.request)
            .then(response => response || fetch(event.request))
    );
});
```

## 5. How to Test

1. [Serve files locally](https://www.mindstick.com/interview/34348/what-is-a-service-worker-and-how-does-it-differ-from-a-traditional-javascript-script) using HTTPS or `localhost` (e.g., with `npx http-server` or Live Server in VS Code).
2. Open the site in Chrome.
3. Check **DevTools → Application → Service Workers** — you should see it active.
4. Load once, then go **offline** and refresh — the cached files will still load.


---

Original Source: https://www.mindstick.com/interview/34351/minimal-offline-ready-service-worker-example

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
