TExcelTAD
Home › 3D Web Games with Three.js › The Loading Manager

The Loading Manager

A game shouldn't start with half its textures missing or a character popping in two seconds late. Before play begins you load everything the first level needs, show progress while that happens, and only then reveal the scene. Three.js coordinates this with THREE.LoadingManager: every loader you create with the same manager reports to it, and the manager tells you when loading starts, how far along it is, and when everything is done.

The callbacks

js
const manager = new THREE.LoadingManager();
manager.onStart = (url, loaded, total) => { /* first item started */ };
manager.onProgress = (url, loaded, total) => { bar.style.width = `${(loaded / total) * 100}%`; };
manager.onLoad = () => { startGame(); };            // everything finished
manager.onError = (url) => { showError(url); };

const textures = new THREE.TextureLoader(manager);
const gltf = new GLTFLoader(manager);
const audio = new THREE.AudioLoader(manager);

onProgress counts items (files), not bytes: a 20 MB level and a 2 KB icon each count as one. For a byte-accurate bar, use the per-file progress callback of loader.load(url, onLoad, onProgress) (it receives the browser's ProgressEvent with loaded and total bytes, when the server sends a length) and sum it yourself.

The manager is a counter. Each loader calls itemStart(url) when a file starts and itemEnd(url) when it finishes, and the manager fires onLoad when the two counts meet. This plain-JS model of it shows a subtlety:

js · try it yourself
// A minimal model of THREE.LoadingManager's counting.
class Manager {
  loaded = 0; total = 0; loading = false;
  log = (msg) => console.log(msg);
  itemStart(url) {
    this.total++;
    if (!this.loading) this.log(`onStart    ${url}`);
    this.loading = true;
  }
  itemEnd(url) {
    this.loaded++;
    this.log(`onProgress ${url.padEnd(14)} ${this.loaded}/${this.total}`);
    if (this.loaded === this.total) { this.loading = false; this.log('onLoad'); }
  }
}

const m = new Manager();
m.itemStart('grass.png');
m.itemStart('hero.glb');
m.itemEnd('grass.png');
m.itemEnd('hero.glb');            // all known items are done -> onLoad fires...
m.itemStart('music.ogg');         // ...but the game asked for one more file afterwards
m.itemEnd('music.ogg');
onStart    grass.png
onProgress grass.png      1/2
onProgress hero.glb       2/2
onLoad
onStart    music.ogg
onProgress music.ogg      3/3
onLoad

onLoad fires whenever the count catches up, so if you start a load after the others finished (or only when the first one completes, as happens with a model whose textures are discovered while parsing), you get onLoad twice. Start every load up front, or use promises for the things the game really waits for.

A loading screen

The playground below creates a few textures from data: URLs (standing in for files) and registers two extra "work items" by hand with itemStart/itemEnd, for things that aren't files, such as generating terrain or compiling shaders. A progress bar fills, and the scene fades in when the manager reports onLoad:

html · try it yourself
<style>html, body { margin: 0; height: 100%; overflow: hidden; background: #0d1018 } canvas { display: block }
#loading { position: fixed; inset: 0; display: grid; place-content: center; gap: 10px; background: #0d1018; color: #cfd8e3; font: 14px system-ui, sans-serif; text-align: center; transition: opacity .6s }
#bar { width: 240px; height: 8px; border-radius: 4px; background: #253045; overflow: hidden }
#fill { width: 0; height: 100%; background: #4fc3f7; transition: width .2s }</style>
<div id="loading"><div id="label">Loading…</div><div id="bar"><div id="fill"></div></div></div>
<script type="module">
import * as THREE from 'three';

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#1c2333');
const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 50);
camera.position.set(0, 1.5, 6);
camera.lookAt(0, 0, 0);
scene.add(new THREE.HemisphereLight('#fff', '#445', 1.5));
const sun = new THREE.DirectionalLight('#fff', 2);
sun.position.set(2, 4, 4);
scene.add(sun);

const manager = new THREE.LoadingManager();
const fill = document.getElementById('fill'), label = document.getElementById('label');
manager.onProgress = (url, loaded, total) => {
  fill.style.width = `${(loaded / total) * 100}%`;
  label.textContent = `Loading ${loaded} / ${total}`;
};
manager.onLoad = () => {
  console.log('all items loaded: starting the game');
  document.getElementById('loading').style.opacity = 0;
  renderer.setAnimationLoop(loop);                 // start rendering only now
};
manager.onError = (url) => console.log('failed:', url.slice(0, 40));

// "Files": small images painted on a canvas and encoded as data: URLs.
function paint(hue) {
  const c = document.createElement('canvas');
  c.width = c.height = 64;
  const g = c.getContext('2d');
  for (let y = 0; y < 8; y++) for (let x = 0; x < 8; x++) {
    g.fillStyle = `hsl(${hue + ((x + y) % 2) * 25}, 60%, ${45 + ((x * 3 + y * 5) % 4) * 6}%)`;
    g.fillRect(x * 8, y * 8, 8, 8);
  }
  return c.toDataURL('image/png');
}
const loader = new THREE.TextureLoader(manager);
const cubes = [10, 120, 200, 300].map((hue, i) => {
  const tex = loader.load(paint(hue));             // returns at once; the image arrives later
  tex.colorSpace = THREE.SRGBColorSpace;
  tex.magFilter = THREE.NearestFilter;
  const cube = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ map: tex }));
  cube.position.x = (i - 1.5) * 1.6;
  scene.add(cube);
  return cube;
});

// Work that is not a file can join the same progress bar.
function fakeTask(name, ms) {
  manager.itemStart(name);
  setTimeout(() => manager.itemEnd(name), ms);
}
fakeTask('generate-terrain', 700);
fakeTask('warm-up-shaders', 1200);

function loop(t) {
  for (const c of cubes) c.rotation.set(t / 2500, t / 1800, 0);
  renderer.render(scene, camera);
}
</script>

Every loader that takes the manager in its constructor (TextureLoader, GLTFLoader, AudioLoader, FileLoader …) reports to it automatically, including the textures a glTF file references. If you create loaders without a manager they report to THREE.DefaultLoadingManager, which you can also attach callbacks to.

Promises: loadAsync and Promise.all

For the game's own control flow, promises read better than callbacks. Every loader has loadAsync:

js
const [hero, level, coinTex] = await Promise.all([
  gltfLoader.loadAsync('models/hero.glb'),
  gltfLoader.loadAsync('models/level1.glb'),
  textureLoader.loadAsync('textures/coin.png'),
]);

Use both together: the manager drives the progress bar, Promise.all decides when the game can start. Wrap it in try/catch and show a real error screen with a retry button; a frozen loading bar is the worst possible first impression.

Avoiding the first-frame hitch

Even after every file is in memory, the first frame that shows a new material compiles its shader and uploads its textures, which can freeze the game for a fraction of a second (or several on a phone). Do that work behind the loading screen:

js
await renderer.compileAsync(scene, camera);          // compile every material's shader program
scene.traverse((o) => {
  if (o.material?.map) renderer.initTexture(o.material.map);   // upload textures now, not on first sight
});

compileAsync uses the KHR_parallel_shader_compile extension where available, so the page stays responsive while shaders compile. Do the same when a new level or a new enemy type is about to appear.

Loading strategies for games

Strategy How Good for
Load everything up front one manager, one loading screen small games, game jams
Per-level loading dispose the old level, load the next behind a transition level-based games
Load the first level, stream the rest start playing, loadAsync the next area in the background larger worlds
Placeholder then swap show a low-res texture or proxy box, replace when the real asset arrives open worlds, user content

Whatever you choose, cache: the browser's HTTP cache (correct Cache-Control headers), THREE.Cache.enabled = true for files requested twice in one session, and a service worker for offline play.

Test yourself

What does LoadingManager.onProgress count?

  1. Bytes downloaded
  2. Items (files and manual itemStart/itemEnd work) finished vs started
  3. Frames rendered
  4. Textures uploaded to the GPU

Why can onLoad fire more than once?

  1. It is a bug in Three.js
  2. It fires whenever the finished count catches up with the started count; items started later start a new round
  3. It fires once per loader
  4. It fires once per texture

Everything is loaded, yet the game stutters the first time a new enemy appears. What helps?

  1. THREE.Cache.enabled = true
  2. Compile shaders and upload textures in advance with renderer.compileAsync and renderer.initTexture
  3. Increase devicePixelRatio
  4. Use loadAsync instead of load