HTML5 game publishing

Offline HTML5 Games: Service Worker Precache and Its Limits

What a service worker can and cannot do for a game on a portal, a minimal precache worker, the update trap, storage limits and making the game itself offline-safe.

PlayKovo Team4 min read
Games currently available on PlayKovo. Open a title to see its current listing.

"No wifi games" is a real search, and so is "games that work offline". Players want to play on a plane, a train or a bad connection. A browser game can support this, but it has limits that are worth stating honestly before you spend a week on it. This post explains what a service worker can and cannot do for an HTML5 game, how to precache the files safely, and the traps that make an "offline" game break its own updates.

What offline means for a browser game

A web page has to be loaded from somewhere. "Offline" support means that after the player has visited once, the browser holds copies of every file the game needs, so the next visit works with no network. The mechanism is a service worker that intercepts requests and answers them from the Cache Storage.

Three things it cannot do:

  • It cannot work on the first visit. The files must have been downloaded online at least once.
  • It cannot fetch anything online-only. Ads, leaderboards, cloud saves and multiplayer will all fail, so the game must handle that.
  • It cannot be assumed on a portal. If your game is hosted inside an iframe on someone else's domain, whether your service worker can register, and what scope it gets, depends on how the files are served. Many portals serve games from a path or domain you do not control. Test it where the game will actually run, and design the game to work perfectly without it.

So treat offline support as a bonus for sites where it works, not as a feature your game depends on. Check the rules of the platform you are submitting to as well. A portal's checks may reject or ignore files such as a service worker, and our post on files PlayKovo ignores or rejects in a game zip lists what to expect there.

A minimal service worker that precaches the game

Register it from the game page:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('./sw.js').catch(() => {});
  });
}

The catch matters. If registration fails, the game must carry on. The worker itself:

const CACHE = 'mygame-v12';
const FILES = [
  './', './index.html', './game.js', './style.css',
  './assets/atlas.png', './assets/sounds.mp3'
];

self.addEventListener('install', e => {
  e.waitUntil(caches.open(CACHE).then(c => c.addAll(FILES)));
  self.skipWaiting();
});

self.addEventListener('activate', e => {
  e.waitUntil(
    caches.keys().then(keys =>
      Promise.all(keys.filter(k => k !== CACHE).map(k => caches.delete(k)))
    ).then(() => self.clients.claim())
  );
});

self.addEventListener('fetch', e => {
  if (e.request.method !== 'GET') return;
  e.respondWith(
    caches.match(e.request).then(hit => hit || fetch(e.request))
  );
});

Use relative paths. A game hosted in a subfolder breaks the moment you write /game.js. See relative asset paths and script order.

The update trap

The most common service worker bug in games is permanent staleness. A cache-first worker serves the old files forever, so players never see your fix. To avoid it:

  • Change the cache name on every release. That is what the mygame-v12 string is for. The activate step deletes older caches.
  • Keep the file list in sync. Generate it at build time instead of editing by hand. A file missing from the list silently fails offline.
  • Do not cache the worker file itself aggressively. The browser checks it for changes, but a long server cache on sw.js can delay updates by hours.
  • Tell the player. If a new worker is waiting, show a small "update ready, reload" message instead of silently swapping files in the middle of a session.

This overlaps with a wider problem covered in preventing cached files from breaking game updates, and the lessons there apply to every cache you use.

Be careful with size and storage

Cache Storage is not unlimited. Browsers apply a quota per origin, and on some devices the storage can be cleared when space is low. Precaching 80 MB of audio to enable offline play is a large ask of a phone. Practical steps:

  • Precache only what is needed for the core loop. Lazy-cache the rest on first use.
  • Keep the total small. A smaller game also loads faster for everyone, which our size reduction checklist covers.
  • Handle a failed addAll. If one file cannot be cached, the whole install fails. For optional assets, cache them one by one inside a try/catch.

Make the game itself offline-safe

A service worker is only half of offline support. The game must not break when the network is missing:

  1. Detect failure fast. Use short timeouts for network calls, as in a boot sequence that cannot hang.
  2. Save progress locally and sync later. Cloud save with a local fallback shows the pattern.
  3. Never block the first screen on an ad or leaderboard request.
  4. Test with the browser's offline mode in DevTools, and also with throttled "slow 3G", which is where most real failures show up.

What to tell players

If your game does support offline play on your own site, say it in specific terms: "Play without a connection after your first visit." Do not claim it on a portal page unless you have tested it in that exact environment. A promise that fails in the airport is worse than no promise.

We use optional cookies for site analytics and site advertising. You can change your choice later. Privacy policy.