Asset Manager
Loads images, sounds, JSON, text and fonts once, keeps them cached, shows loading progress, retries failed files and lists anything missing.
Files: asset-manager.js (the component, no dependencies) and asset-manager.test.mjs (6 tests).
Copy asset-manager.js into your game, for example to src/components/, and import it as an ES module.
Usage
import { createAssets } from "./asset-manager.js";
const assets = createAssets({ baseUrl: "assets/" });
assets.add({ hero: "sprites/hero.png", level1: "levels/1.json", theme: "music/theme.ogg", title: { url: "fonts/title.woff2", family: "Title" } });
const result = await assets.loadAll((done, total) => drawLoadingBar(done / total));
if (result.failed.length) showError(result.failed); // [{ name, url, error }]
ctx.drawImage(assets.get("hero"), x, y);
API
createAssets({ baseUrl, retries, loaders, audioContext, fetch }) → assetsassets.add(name, url | { url, type, optional, family }) or assets.add({ name: url, ... })assets.loadAll(onProgress) → { loaded: [...names], failed: [...] }; rejects only if a required (not optional) file failed and throwOnFail is setassets.load(name) → Promise of one asset (cached; the same URL is fetched once even under two names)assets.get(name)the loaded asset; throws with a clear message if it isn’t loadedassets.has(name) / assets.unload(name) / assets.progress (0..1) / assets.missing (names asked for with get() that failed)
Types come from the extension: png jpg jpeg gif webp svg avif → image; json → json; txt csv glsl → text;
data: URLs use their MIME type (data:image/png → image).
ogg mp3 wav m4a → audio (decoded with audioContext if given, else an ArrayBuffer); woff woff2 ttf otf → font. Add your own in loaders.
Engines
| Engine | Notes |
|---|---|
| Vanilla | yes. |
| Phaser | use Phaser’s loader in preload() instead. |
| PixiJS | use PIXI.Assets for textures; this one still helps for JSON, text and sound. |
| Three.js | yes. Add a loader for models, e.g. loaders: { gltf: (url) => new GLTFLoader().loadAsync(url) }. |
Tests
Node tests with fake loaders: types by extension, caching and shared URLs, progress, retries, optional files, failure list, clear errors on get().
Run them with node --test toolkit/components/asset-manager/ (Node 20 or newer, nothing to install).