As your 3D web experiences grow in complexity, so does the amount of data you need to load and manage. Efficiently handling assets like 3D models, textures, and audio is crucial for a smooth user experience. Slow loading times can frustrate users and lead to them abandoning your creation. This section will guide you through best practices for loading and managing your assets effectively in Three.js.
One of the most fundamental ways to manage assets is through organized loading. For larger projects, it's impractical to load everything at once. A common approach is to use a loading manager to track the progress of multiple files and execute specific functions once all assets are loaded.
const manager = new THREE.LoadingManager();
manager.onStart = function ( url, itemsLoaded, itemsTotal ) {
console.log( 'Started loading file: ' + url + '.' );
console.log( 'Number of files loaded: ' + itemsLoaded + ' of ' + itemsTotal );
};
manager.onLoad = function ( ) {
console.log( 'All files loaded.' );
// Start your scene animation or setup here
};
manager.onProgress = function ( url, itemsLoaded, itemsTotal ) {
console.log( 'Loading file: ' + url );
console.log( 'Progress: ' + itemsLoaded + ' / ' + itemsTotal );
};
manager.onError = function ( url ) {
console.error( 'There was an error loading: ' + url );
};
const loader = new THREE.GLTFLoader( manager );
loader.load( 'path/to/your/model.glb', function ( gltf ) {
// Model loaded, add to scene
scene.add( gltf.scene );
});
const textureLoader = new THREE.TextureLoader( manager );
const texture = textureLoader.load( 'path/to/your/texture.jpg' );The THREE.LoadingManager provides callbacks for onStart, onLoad, onProgress, and onError. This allows you to display loading progress to the user, hide a loading screen, and then initialize your scene once everything is ready. Notice how you can pass the manager instance to individual loaders like GLTFLoader and TextureLoader.
When dealing with 3D models, the file format significantly impacts loading times and memory usage. For web applications, the GL Transmission Format (glTF) and its binary counterpart (GLB) are the recommended standards. They are designed to be efficient, compact, and well-supported by Three.js.
Consider these benefits of glTF/GLB:
- Compactness: GLB files package all assets (model, textures, etc.) into a single binary file, reducing overhead.
- Efficiency: glTF is optimized for efficient runtime loading and rendering.
- Feature Support: Supports PBR materials, animations, and more.