How to Use Three.js TextureLoader Callbacks
Loading textures asynchronously in Three.js can cause rendering
delays or visual glitches if your 3D objects are rendered before their
textures have fully downloaded. This article explains how to utilize the
callback functions of the Three.js TextureLoader
class—specifically the onLoad callback—to pause rendering,
hide loading screens, or trigger custom application logic only after an
image has successfully loaded.
Understanding TextureLoader.load()
The .load() method of the TextureLoader
class accepts four arguments: the image URL and three optional callback
functions.
loader.load( url, onLoad, onProgress, onError );url(String): The path or URL to the image file.onLoad(Function): Triggered after the texture finishes downloading and is ready to use. This is where you place your post-load logic.onProgress(Function): Historically used for download progress, but currently not supported for individual textures in Three.js (it will returnundefined).onError(Function): Triggered if the image fails to load.
Practical Code Example
In the example below, we initialize a TextureLoader,
load an image, and use the onLoad callback to apply the
texture to a material, add the mesh to the scene, and trigger a custom
function to start the application.
import * as THREE from 'three';
// Initialize your scene, camera, and renderer
const scene = new THREE.Scene();
const loader = new THREE.TextureLoader();
// 1. Load the texture and define callbacks
loader.load(
'path/to/your/texture.jpg',
// onLoad callback
function ( texture ) {
// This logic runs ONLY after the image loads successfully
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { map: texture } );
const mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
// Trigger post-loading logic
initializeApplication();
},
// onProgress callback (not supported, pass undefined)
undefined,
// onError callback
function ( err ) {
console.error( 'An error occurred while loading the texture.', err );
}
);
function initializeApplication() {
console.log( 'Texture is loaded. Starting the animation loop...' );
// Place code here to hide loading screens or start game loops
}Why Use the onLoad Callback?
Using the onLoad callback is critical for several common
web development scenarios:
- Preventing “Pop-in”: By default, Three.js will
render a material as solid black or white until the texture loads,
creating an ugly visual jump. Delaying object visibility until
onLoadfires prevents this. - Loading Screens: You can display a loading spinner
when your application starts and remove it only when the
onLoadcallback resolves. - Dynamic Asset Swapping: If you are changing
textures at runtime based on user interaction, you can disable interface
buttons during loading and re-enable them once the
onLoadcallback fires.