Map-style web apps, whether they show game worlds, floor plans or satellite imagery, usually split the view into square tiles and request only the tiles on screen. When users pan back and forth, refetching the same tiles wastes bandwidth and makes the map feel slow. This post shows a small tile cache built on IndexedDB, with a memory layer in front, in about 60 lines of plain JavaScript.
Tile keys
Every tile needs a stable key. For a world map that depends on a seed and a game version, include everything that changes the image:
const tileKey = ({ seed, version, layer, z, x, y }) =>
`${version}/${seed}/${layer}/${z}/${x}/${y}`;
If you forget a parameter (say, the version), users will see stale tiles from another configuration.
A tiny IndexedDB wrapper
function openDb() {
return new Promise((resolve, reject) => {
const req = indexedDB.open("tile-cache", 1);
req.onupgradeneeded = () => req.result.createObjectStore("tiles");
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
const dbPromise = openDb();
async function idbGet(key) {
const db = await dbPromise;
return new Promise((resolve, reject) => {
const req = db.transaction("tiles").objectStore("tiles").get(key);
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
async function idbPut(key, value) {
const db = await dbPromise;
return new Promise((resolve, reject) => {
const tx = db.transaction("tiles", "readwrite");
tx.objectStore("tiles").put(value, key);
tx.oncomplete = resolve;
tx.onerror = () => reject(tx.error);
});
}
Two-level cache
const memory = new Map();
const MAX_MEMORY = 300; // tiles
async function getTile(params, fetchTile) {
const key = tileKey(params);
if (memory.has(key)) return memory.get(key);
let entry = await idbGet(key);
if (!entry) {
const blob = await fetchTile(params); // network or generator
entry = { blob, savedAt: Date.now() };
idbPut(key, entry).catch(() => {}); // ignore quota errors
}
const bitmap = await createImageBitmap(entry.blob);
memory.set(key, bitmap);
if (memory.size > MAX_MEMORY) {
const oldest = memory.keys().next().value; // Map keeps insertion order
memory.get(oldest).close();
memory.delete(oldest);
}
return bitmap;
}
Blobs go into IndexedDB because they survive reloads; decoded ImageBitmaps live only in memory because they are fast to draw but large.
Expiry and quota
- Store a
savedAttimestamp and treat entries older than, say, 30 days as missing. - Browsers can evict IndexedDB data under storage pressure. Call
navigator.storage.persist()if your app benefits from keeping tiles, and always handle a cache miss gracefully. - Check usage with
navigator.storage.estimate()and clear old layers when the user switches projects.
Drawing
async function drawVisible(ctx, view, fetchTile) {
for (const t of view.visibleTiles()) {
const bmp = await getTile(t, fetchTile);
ctx.drawImage(bmp, t.screenX, t.screenY, view.tileSize, view.tileSize);
}
}
In a real app, request tiles in parallel and draw each as it arrives instead of awaiting them one by one.
Where this pattern shows up
Game world viewers are a good example: the same seed and version always produce the same terrain, so tiles are perfectly cacheable. The interactive map on Minecraft Seed Map is the kind of interface where caching like this makes panning around a large world feel instant, and the same approach works for any deterministic tile source.
Top comments (0)