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 );

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: