A browser game should feel instant.
Players don't want to wait for a network request every time they answer a question. And if their connection disappears halfway through a round, losing all progress can be frustrating.
For a small trivia game, an offline-first approach is surprisingly achievable.
You don't necessarily need a backend, a database server, or a complicated Progressive Web App framework.
A Service Worker and a local question bank can provide a useful starting point.
In this tutorial, we'll build a minimal offline-capable trivia game architecture using vanilla JavaScript.
1. Decide What Actually Needs the Network
Imagine a trivia game with the following features:
- A collection of questions
- Multiple accepted answers per question
- A local scoring system
- A countdown timer
- A results screen
Most of these features don't need a server connection during gameplay.
The questions can be loaded from a JSON file. Answer validation and scoring can happen locally, and the countdown can use the browser's own clock.
The main reason to use the network is to download the application and its data.
This makes trivia games good candidates for offline-first architecture.
2. Store Questions in a JSON File
Let's start with a small question bank.
Create a file named questions.json:
[
{
"id": "birds",
"prompt": "Name a bird",
"answers": {
"eagle": 10,
"oilbird": 85,
"hoatzin": 100
}
},
{
"id": "fruits",
"prompt": "Name a fruit",
"answers": {
"apple": 10,
"salak": 85,
"feijoa": 100
}
}
]
These rarity scores are hypothetical examples, not measured player statistics.
In a production game, you would probably want a richer data model with canonical answer names, aliases, prompt-specific restrictions, and a consistent scoring policy.
But for an offline demo, this structure is enough.
The important point is that the browser can load the question bank once and reuse it without contacting an API for every answer.
3. Register a Service Worker
A Service Worker is a JavaScript file that can intercept supported network requests and serve cached responses.
First, register it in your application's JavaScript:
if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker
.register("/sw.js")
.catch((error) => {
console.error(
"Service Worker registration failed:",
error
);
});
});
}
Service Workers generally require HTTPS, although localhost is supported during development.
Registration alone doesn't make an application work offline. We still need to define what gets cached.
4. Cache the Application Shell
Create a file called sw.js at the site's root.
For this example, assume our application consists of:
index.html
app.js
styles.css
questions.json
We'll cache those files during installation.
const CACHE_NAME = "trivia-static-v1";
const ASSETS = [
"/",
"/index.html",
"/app.js",
"/styles.css",
"/questions.json"
];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(ASSETS);
})
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then((keys) => {
return Promise.all(
keys
.filter(
(key) =>
key.startsWith("trivia-static-") &&
key !== CACHE_NAME
)
.map((key) => caches.delete(key))
);
})
);
});
When the Service Worker installs successfully, the Cache Storage API stores the required files.
Make sure the paths in ASSETS actually exist on your server. If a required file fails to download, the cache installation can fail.
For production applications, these assets are often generated automatically by a build tool.
5. Serve Cached Files When Offline
Next, add a fetch handler to sw.js.
self.addEventListener("fetch", (event) => {
const request = event.request;
const url = new URL(request.url);
if (request.method !== "GET") return;
if (url.origin !== self.location.origin) return;
if (request.mode === "navigate") {
event.respondWith(
fetch(request).catch(async () => {
return (
(await caches.match(request)) ||
caches.match("/index.html")
);
})
);
return;
}
if (ASSETS.includes(url.pathname)) {
event.respondWith(
caches.match(request).then((cached) => {
return cached || fetch(request);
})
);
}
});
This example uses two strategies.
Navigation requests: Try the network first. If the network fails, use a cached page or the application shell.
Precached assets: Prefer the cached response, avoiding unnecessary network requests.
Because the question bank is cached, the game can still retrieve its data when the user loses connectivity.
This example assumes a simple, single-page application with a real index.html file. Different routing systems may need a different navigation fallback strategy.
6. Load the Question Bank Normally
The application doesn't need to know whether a response came from the network or the Service Worker cache.
It can use the normal Fetch API:
async function loadQuestions() {
const response = await fetch("/questions.json");
if (!response.ok) {
throw new Error("Failed to load questions");
}
return response.json();
}
When online, the Service Worker can return the precached file.
When offline, the same cached response remains available.
This means the rest of the trivia game's logic can remain independent of the caching implementation.
7. Test the Offline Experience
The easiest way to test this is through Chrome DevTools.
First, serve the project locally and open it in your browser.
Then:
- Open DevTools and navigate to Application → Service Workers.
- Confirm that the Service Worker has installed.
- Check Application → Cache Storage to verify the files were cached.
- Reload the page after installation.
- Simulate an offline connection.
- Reload again and try answering a question.
If the application shell and question data are cached correctly, the game should remain usable.
Remember that offline functionality generally requires a successful online visit first.
A player opening the site for the first time without an internet connection won't have the necessary files cached.
Also, browsers can evict stored data under storage pressure, so offline availability shouldn't be treated as an absolute guarantee.
8. What About Game Progress?
Caching the application files solves only part of the problem.
If users should be able to resume a game after closing the browser, their progress must also be saved.
For a small game, localStorage can handle simple state