JavaScript 3D library providing WebGL and WebGPU renderers for creating interactive 3D graphics in web browsers
—
Three.js provides a comprehensive asset loading system for 3D models, textures, audio, and other media with progress tracking, error handling, and caching capabilities. The loading system supports various file formats and provides both callback-based and Promise-based APIs.
Central coordination system for managing multiple asset loads with global progress tracking and error handling.
/**
* Manages loading of multiple assets with progress tracking and coordination
*/
class LoadingManager {
/**
* Create loading manager with optional callbacks
* @param onLoad - Called when all items finish loading
* @param onProgress - Called when any item reports progress
* @param onError - Called when any item fails to load
*/
constructor(
onLoad?: () => void,
onProgress?: (url: string, itemsLoaded: number, itemsTotal: number) => void,
onError?: (url: string) => void
);
/** Callback when all items finish loading */
onLoad: (() => void) | undefined;
/** Callback for progress updates */
onProgress: ((url: string, itemsLoaded: number, itemsTotal: number) => void) | undefined;
/** Callback for loading errors */
onError: ((url: string) => void) | undefined;
/** Callback when loading starts */
onStart: ((url: string, itemsLoaded: number, itemsTotal: number) => void) | undefined;
/**
* Register item as loading
* @param url - URL being loaded
*/
itemStart(url: string): void;
/**
* Register item as completed loading
* @param url - URL that finished loading
*/
itemEnd(url: string): void;
/**
* Handle loading error for item
* @param url - URL that failed to load
*/
itemError(url: string): void;
/**
* Resolve URL using URL resolver function
* @param url - URL to resolve
* @returns Resolved URL
*/
resolveURL(url: string): string;
/**
* Set URL modifier function for rewriting URLs
* @param callback - Function to modify URLs before loading
*/
setURLModifier(callback?: (url: string) => string): LoadingManager;
/**
* Add regex handler for transforming URLs
* @param regex - Pattern to match URLs
* @param callback - Function to transform matching URLs
*/
addHandler(regex: RegExp, loader: Loader): LoadingManager;
/**
* Remove URL handler
* @param regex - Pattern to remove handler for
*/
removeHandler(regex: RegExp): LoadingManager;
/**
* Get appropriate loader for URL
* @param file - URL to find loader for
* @returns Loader instance or null
*/
getHandler(file: string): Loader | null;
}
/** Default global loading manager instance */
declare const DefaultLoadingManager: LoadingManager;Usage Example:
import { LoadingManager, TextureLoader, GLTFLoader } from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
// Create manager with progress tracking
const manager = new LoadingManager(
() => console.log('All assets loaded!'),
(url, loaded, total) => console.log(`Loading: ${loaded}/${total} - ${url}`),
(url) => console.error(`Failed to load: ${url}`)
);
// Use manager with loaders
const textureLoader = new TextureLoader(manager);
const gltfLoader = new GLTFLoader(manager);
// Load multiple assets
const texture = textureLoader.load('texture.jpg');
gltfLoader.load('model.gltf', (gltf) => {
scene.add(gltf.scene);
});Abstract base class providing common functionality for all asset loaders.
/**
* Base class for all Three.js asset loaders
*/
abstract class Loader<TData = any> {
/**
* Create loader with optional loading manager
* @param manager - Loading manager to coordinate with
*/
constructor(manager?: LoadingManager);
/** Loading manager coordinating this loader */
manager: LoadingManager;
/** Base path for resolving relative URLs */
path: string;
/** Base resource path for resolving relative URLs */
resourcePath: string;
/** Request headers to send with load requests */
requestHeader: { [header: string]: string };
/** Credentials mode for cross-origin requests */
crossOrigin: string;
/** Whether to include credentials in requests */
withCredentials: boolean;
/**
* Load asset from URL
* @param url - Asset URL to load
* @param onLoad - Success callback with loaded data
* @param onProgress - Progress callback
* @param onError - Error callback
* @returns Loaded data or loading placeholder
*/
abstract load(
url: string,
onLoad?: (data: TData) => void,
onProgress?: (event: ProgressEvent) => void,
onError?: (event: ErrorEvent) => void
): TData;
/**
* Load multiple assets in parallel
* @param urls - Array of URLs to load
* @param onLoad - Success callback with array of loaded data
* @param onProgress - Progress callback
* @param onError - Error callback
*/
loadAsync(url: string): Promise<TData>;
/**
* Set base path for resolving relative URLs
* @param path - Base path to use
* @returns This loader for chaining
*/
setPath(path: string): this;
/**
* Set resource path for resolving resource URLs
* @param resourcePath - Resource path to use
* @returns This loader for chaining
*/
setResourcePath(resourcePath: string): this;
/**
* Set request headers for HTTP requests
* @param requestHeader - Headers object
* @returns This loader for chaining
*/
setRequestHeader(requestHeader: { [header: string]: string }): this;
}Specialized loader for image textures with support for various image formats and texture configuration.
/**
* Loads images as Three.js textures with automatic format detection
*/
class TextureLoader extends Loader<Texture> {
/**
* Create texture loader
* @param manager - Optional loading manager
*/
constructor(manager?: LoadingManager);
/**
* Load texture from image URL
* @param url - Image URL to load
* @param onLoad - Success callback with loaded texture
* @param onProgress - Progress callback
* @param onError - Error callback
* @returns Texture object (loads asynchronously)
*/
load(
url: string,
onLoad?: (texture: Texture) => void,
onProgress?: (event: ProgressEvent) => void,
onError?: (event: ErrorEvent) => void
): Texture;
/**
* Load texture asynchronously with Promise
* @param url - Image URL to load
* @returns Promise resolving to loaded texture
*/
loadAsync(url: string): Promise<Texture>;
}Usage Example:
import { TextureLoader, MeshBasicMaterial, PlaneGeometry, Mesh } from 'three';
const loader = new TextureLoader();
// Load texture with callbacks
const texture = loader.load(
'path/to/texture.jpg',
(texture) => {
console.log('Texture loaded:', texture);
// Texture is ready to use
},
(progress) => {
console.log('Loading progress:', progress.loaded / progress.total);
},
(error) => {
console.error('Loading failed:', error);
}
);
// Use texture immediately (will appear when loaded)
const material = new MeshBasicMaterial({ map: texture });
const geometry = new PlaneGeometry(1, 1);
const mesh = new Mesh(geometry, material);
// Or load with async/await
async function loadTexture() {
try {
const texture = await loader.loadAsync('path/to/texture.jpg');
const material = new MeshBasicMaterial({ map: texture });
// Use material...
} catch (error) {
console.error('Failed to load texture:', error);
}
}Loader for cube textures used in environment mapping and skyboxes.
/**
* Loads six images as cube texture for environment mapping
*/
class CubeTextureLoader extends Loader<CubeTexture> {
/**
* Create cube texture loader
* @param manager - Optional loading manager
*/
constructor(manager?: LoadingManager);
/**
* Load cube texture from six image URLs
* @param urls - Array of 6 image URLs [+X, -X, +Y, -Y, +Z, -Z]
* @param onLoad - Success callback with loaded cube texture
* @param onProgress - Progress callback
* @param onError - Error callback
* @returns CubeTexture object (loads asynchronously)
*/
load(
urls: string[],
onLoad?: (texture: CubeTexture) => void,
onProgress?: (event: ProgressEvent) => void,
onError?: (event: ErrorEvent) => void
): CubeTexture;
/**
* Load cube texture asynchronously with Promise
* @param urls - Array of 6 image URLs
* @returns Promise resolving to loaded cube texture
*/
loadAsync(urls: string[]): Promise<CubeTexture>;
}Low-level loader for arbitrary file types with configurable response types.
/**
* Generic file loader supporting various response types
*/
class FileLoader extends Loader<string | ArrayBuffer> {
/**
* Create file loader
* @param manager - Optional loading manager
*/
constructor(manager?: LoadingManager);
/** MIME type for requests */
mimeType: string | undefined;
/** Response type for XMLHttpRequest */
responseType: string | undefined;
/**
* Load file from URL
* @param url - File URL to load
* @param onLoad - Success callback with file data
* @param onProgress - Progress callback
* @param onError - Error callback
* @returns File data (string or ArrayBuffer based on responseType)
*/
load(
url: string,
onLoad?: (data: string | ArrayBuffer) => void,
onProgress?: (event: ProgressEvent) => void,
onError?: (event: ErrorEvent) => void
): string | ArrayBuffer;
/**
* Set MIME type for requests
* @param mimeType - MIME type string
* @returns This loader for chaining
*/
setMimeType(mimeType: string): this;
/**
* Set response type for XMLHttpRequest
* @param responseType - Response type ('text', 'arraybuffer', 'blob', 'document', 'json')
* @returns This loader for chaining
*/
setResponseType(responseType: string): this;
}Specialized loaders for different image loading scenarios.
/**
* Loads images as HTML Image elements
*/
class ImageLoader extends Loader<HTMLImageElement> {
/**
* Create image loader
* @param manager - Optional loading manager
*/
constructor(manager?: LoadingManager);
/**
* Load image from URL
* @param url - Image URL to load
* @param onLoad - Success callback with loaded image
* @param onProgress - Progress callback (may not be supported)
* @param onError - Error callback
* @returns HTMLImageElement (loads asynchronously)
*/
load(
url: string,
onLoad?: (image: HTMLImageElement) => void,
onProgress?: (event: ProgressEvent) => void,
onError?: (event: ErrorEvent) => void
): HTMLImageElement;
}
/**
* Loads images as ImageBitmap objects for high-performance usage
*/
class ImageBitmapLoader extends Loader<ImageBitmap> {
/**
* Create ImageBitmap loader
* @param manager - Optional loading manager
*/
constructor(manager?: LoadingManager);
/** Options for createImageBitmap */
options: ImageBitmapOptions | undefined;
/**
* Load image as ImageBitmap
* @param url - Image URL to load
* @param onLoad - Success callback with ImageBitmap
* @param onProgress - Progress callback
* @param onError - Error callback
* @returns Promise-like object for ImageBitmap
*/
load(
url: string,
onLoad?: (imageBitmap: ImageBitmap) => void,
onProgress?: (event: ProgressEvent) => void,
onError?: (event: ErrorEvent) => void
): any;
/**
* Set options for ImageBitmap creation
* @param options - ImageBitmap creation options
* @returns This loader for chaining
*/
setOptions(options: ImageBitmapOptions): this;
}Loader for raw texture data and specialized texture formats.
/**
* Loads raw data as DataTexture objects
*/
class DataTextureLoader extends Loader<DataTexture> {
/**
* Create data texture loader
* @param manager - Optional loading manager
*/
constructor(manager?: LoadingManager);
/**
* Load raw data as texture
* @param url - Data URL to load
* @param onLoad - Success callback with DataTexture
* @param onProgress - Progress callback
* @param onError - Error callback
* @returns DataTexture object
*/
load(
url: string,
onLoad?: (dataTexture: DataTexture) => void,
onProgress?: (event: ProgressEvent) => void,
onError?: (event: ErrorEvent) => void
): DataTexture;
}Loader for GPU-compressed texture formats for optimized memory usage and performance.
/**
* Loads compressed texture formats (DXT, ETC, ASTC, etc.)
*/
class CompressedTextureLoader extends Loader<CompressedTexture> {
/**
* Create compressed texture loader
* @param manager - Optional loading manager
*/
constructor(manager?: LoadingManager);
/**
* Load compressed texture data
* @param url - Compressed texture URL
* @param onLoad - Success callback with CompressedTexture
* @param onProgress - Progress callback
* @param onError - Error callback
* @returns CompressedTexture object
*/
load(
url: string,
onLoad?: (texture: CompressedTexture) => void,
onProgress?: (event: ProgressEvent) => void,
onError?: (event: ErrorEvent) => void
): CompressedTexture;
}Loaders for Three.js-specific object and material formats.
/**
* Loads Three.js Object3D hierarchies from JSON format
*/
class ObjectLoader extends Loader<Group> {
/**
* Create object loader
* @param manager - Optional loading manager
*/
constructor(manager?: LoadingManager);
/**
* Load Object3D hierarchy from JSON
* @param url - JSON file URL
* @param onLoad - Success callback with loaded object
* @param onProgress - Progress callback
* @param onError - Error callback
* @returns Group object containing loaded hierarchy
*/
load(
url: string,
onLoad?: (object: Group) => void,
onProgress?: (event: ProgressEvent) => void,
onError?: (event: ErrorEvent) => void
): Group;
/**
* Parse JSON data into Object3D hierarchy
* @param json - JSON object data
* @param onLoad - Success callback
* @returns Parsed Object3D
*/
parse<T extends Object3D>(json: any, onLoad?: (object: T) => void): T;
/**
* Parse geometries from JSON data
* @param json - JSON geometry data
* @returns Map of geometry instances
*/
parseGeometries(json: any): { [key: string]: BufferGeometry };
/**
* Parse materials from JSON data
* @param json - JSON material data
* @param textures - Map of loaded textures
* @returns Map of material instances
*/
parseMaterials(json: any, textures: { [key: string]: Texture }): { [key: string]: Material };
/**
* Parse animations from JSON data
* @param json - JSON animation data
* @returns Array of animation clips
*/
parseAnimations(json: any): AnimationClip[];
/**
* Parse images from JSON data
* @param json - JSON image data
* @param onLoad - Callback when all images loaded
* @returns Map of loaded textures
*/
parseImages(json: any, onLoad: () => void): { [key: string]: Texture };
/**
* Parse textures from JSON data
* @param json - JSON texture data
* @param images - Map of loaded images
* @returns Map of texture instances
*/
parseTextures(json: any, images: { [key: string]: Texture }): { [key: string]: Texture };
/**
* Parse objects from JSON data
* @param json - JSON object data
* @param geometries - Map of geometries
* @param materials - Map of materials
* @param animations - Array of animations
* @returns Parsed Object3D
*/
parseObject<T extends Object3D>(
json: any,
geometries: { [key: string]: BufferGeometry },
materials: { [key: string]: Material },
animations: AnimationClip[]
): T;
}
/**
* Loads Three.js materials from JSON format
*/
class MaterialLoader extends Loader<Material> {
/**
* Create material loader
* @param manager - Optional loading manager
*/
constructor(manager?: LoadingManager);
/** Map of loaded textures for material creation */
textures: { [key: string]: Texture };
/**
* Load material from JSON
* @param url - JSON file URL
* @param onLoad - Success callback with loaded material
* @param onProgress - Progress callback
* @param onError - Error callback
* @returns Material object
*/
load(
url: string,
onLoad?: (material: Material) => void,
onProgress?: (event: ProgressEvent) => void,
onError?: (event: ErrorEvent) => void
): Material;
/**
* Parse JSON data into material
* @param json - JSON material data
* @returns Parsed material instance
*/
parse(json: any): Material;
/**
* Set textures map for material parsing
* @param textures - Map of texture instances
* @returns This loader for chaining
*/
setTextures(textures: { [key: string]: Texture }): this;
}
/**
* Loads BufferGeometry from JSON format
*/
class BufferGeometryLoader extends Loader<BufferGeometry> {
/**
* Create buffer geometry loader
* @param manager - Optional loading manager
*/
constructor(manager?: LoadingManager);
/**
* Load geometry from JSON
* @param url - JSON file URL
* @param onLoad - Success callback with loaded geometry
* @param onProgress - Progress callback
* @param onError - Error callback
* @returns BufferGeometry object
*/
load(
url: string,
onLoad?: (geometry: BufferGeometry) => void,
onProgress?: (event: ProgressEvent) => void,
onError?: (event: ErrorEvent) => void
): BufferGeometry;
/**
* Parse JSON data into BufferGeometry
* @param json - JSON geometry data
* @returns Parsed BufferGeometry instance
*/
parse(json: any): BufferGeometry;
}Loader for animation data in Three.js JSON format.
/**
* Loads animation clips from JSON format
*/
class AnimationLoader extends Loader<AnimationClip[]> {
/**
* Create animation loader
* @param manager - Optional loading manager
*/
constructor(manager?: LoadingManager);
/**
* Load animations from JSON
* @param url - JSON file URL containing animation data
* @param onLoad - Success callback with loaded animation clips
* @param onProgress - Progress callback
* @param onError - Error callback
* @returns Array of AnimationClip objects
*/
load(
url: string,
onLoad?: (animations: AnimationClip[]) => void,
onProgress?: (event: ProgressEvent) => void,
onError?: (event: ErrorEvent) => void
): AnimationClip[];
/**
* Parse JSON data into animation clips
* @param json - JSON animation data
* @returns Array of parsed AnimationClip instances
*/
parse(json: any): AnimationClip[];
}Loader for audio files with support for various audio formats.
/**
* Loads audio files as AudioBuffer objects for use with Web Audio API
*/
class AudioLoader extends Loader<AudioBuffer> {
/**
* Create audio loader
* @param manager - Optional loading manager
*/
constructor(manager?: LoadingManager);
/**
* Load audio file
* @param url - Audio file URL
* @param onLoad - Success callback with decoded AudioBuffer
* @param onProgress - Progress callback
* @param onError - Error callback
* @returns AudioBuffer object (decoded asynchronously)
*/
load(
url: string,
onLoad?: (audioBuffer: AudioBuffer) => void,
onProgress?: (event: ProgressEvent) => void,
onError?: (event: ErrorEvent) => void
): AudioBuffer;
}Global caching system for loaded assets to prevent duplicate requests and improve performance.
/**
* Global cache for loaded assets to prevent duplicate requests
*/
class Cache {
/** Whether caching is enabled */
static enabled: boolean;
/** Map of cached files */
static files: { [key: string]: any };
/**
* Add item to cache
* @param key - Cache key (usually URL)
* @param file - Data to cache
*/
static add(key: string, file: any): void;
/**
* Get item from cache
* @param key - Cache key to retrieve
* @returns Cached data or undefined
*/
static get(key: string): any;
/**
* Remove item from cache
* @param key - Cache key to remove
*/
static remove(key: string): void;
/**
* Clear all cached items
*/
static clear(): void;
}Utility functions for working with loaded data and extracting information.
/**
* Utility functions for asset loading operations
*/
class LoaderUtils {
/**
* Extract URL base path for resolving relative URLs
* @param url - Full URL to extract base from
* @returns Base path portion of URL
*/
static extractUrlBase(url: string): string;
/**
* Decode text from array buffer with encoding detection
* @param array - Array buffer containing text data
* @returns Decoded text string
*/
static decodeText(array: Uint8Array): string;
}// Loading-related type definitions
interface ProgressEvent {
lengthComputable: boolean;
loaded: number;
total: number;
target?: any;
}
interface ErrorEvent {
message: string;
target?: any;
}
// ImageBitmap creation options
interface ImageBitmapOptions {
imageOrientation?: 'none' | 'flipY';
premultiplyAlpha?: 'none' | 'premultiply' | 'default';
colorSpaceConversion?: 'none' | 'default';
resizeWidth?: number;
resizeHeight?: number;
resizeQuality?: 'pixelated' | 'low' | 'medium' | 'high';
}Complete Asset Loading Pipeline:
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
// Create loading manager with progress tracking
const loadingManager = new THREE.LoadingManager();
loadingManager.onStart = (url, itemsLoaded, itemsTotal) => {
console.log(`Started loading: ${url}`);
};
loadingManager.onProgress = (url, itemsLoaded, itemsTotal) => {
const progress = itemsLoaded / itemsTotal * 100;
console.log(`Loading progress: ${progress.toFixed(1)}%`);
updateProgressBar(progress);
};
loadingManager.onLoad = () => {
console.log('All assets loaded!');
hideLoadingScreen();
};
loadingManager.onError = (url) => {
console.error(`Failed to load: ${url}`);
};
// Set up loaders with manager
const textureLoader = new THREE.TextureLoader(loadingManager);
const gltfLoader = new GLTFLoader(loadingManager);
// Set up DRACO compression support
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath('/examples/js/libs/draco/');
gltfLoader.setDRACOLoader(dracoLoader);
// Load multiple assets
Promise.all([
textureLoader.loadAsync('textures/ground.jpg'),
textureLoader.loadAsync('textures/sky.jpg'),
gltfLoader.loadAsync('models/character.gltf')
]).then(([groundTexture, skyTexture, gltf]) => {
// All assets loaded, set up scene
groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping;
groundTexture.repeat.set(10, 10);
const groundMaterial = new THREE.MeshLambertMaterial({ map: groundTexture });
const groundGeometry = new THREE.PlaneGeometry(50, 50);
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = -Math.PI / 2;
scene.add(ground);
scene.background = skyTexture;
scene.add(gltf.scene);
// Start animation if present
if (gltf.animations.length > 0) {
const mixer = new THREE.AnimationMixer(gltf.scene);
const action = mixer.clipAction(gltf.animations[0]);
action.play();
// Update mixer in render loop
const clock = new THREE.Clock();
function animate() {
const deltaTime = clock.getDelta();
mixer.update(deltaTime);
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
animate();
}
}).catch((error) => {
console.error('Loading failed:', error);
});Install with Tessl CLI
npx tessl i tessl/npm-three