Hosting & loading 3D assets

Back to Modules

Hosting and Loading 3D Assets in Three.js

Three.js is a powerful JavaScript library for displaying 3D graphics in a web browser. To effectively use 3D models in your Three.js projects, you'll need to understand how to host these assets and then load them into your scene.

Hosting 3D Assets

3D assets, such as models, textures, and animations, are typically static files that need to be served by a web server. Here are common methods for hosting them:

1. Local Development Server:

For development, you can use a simple local HTTP server (e.g., Node.js http-server, Python's http.server, or npx serve). This allows your browser to access the files from your local machine.

npx serve .

2. Content Delivery Network (CDN):

CDNs are highly recommended for production environments. They distribute your assets across multiple servers globally, reducing latency and improving loading times for users worldwide.

3. Cloud Storage Services:

Services like Amazon S3, Google Cloud Storage, or Azure Blob Storage are excellent for hosting static assets. They offer high availability, scalability, and can be integrated with CDNs.

4. Your Own Web Server:

If you have a dedicated web server (e.g., Apache, Nginx), you can place your 3D asset files in a publicly accessible directory.

Loading 3D Assets in Three.js

Three.js uses various "loaders" to import different 3D file formats. The most recommended and widely adopted format for web-based 3D is glTF (GL Transmission Format), often referred to as the "JPEG of 3D" due to its efficiency and suitability for web delivery.

Loading glTF Models with GLTFLoader:

import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

// Instantiate a loader
const loader = new GLTFLoader();

// Load a glTF resource
loader.load(
    // resource URL
    'path/to/your_model.gltf', // or .glb
    // called when the resource is loaded
    function ( gltf ) {
        scene.add( gltf.scene );
    },
    // called while loading is progressing
    function ( xhr ) {
        console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
    },
    // called when loading has errors
    function ( error ) {
        console.error( 'An error happened', error );
    }
);

Other Common Loaders:

While glTF is preferred, Three.js also supports other formats with dedicated loaders:

Important Considerations: