How to Optimize GLB and glTF Files for Three.js

Optimize GLB for Three.js with exact Compatible and Smallest preset settings, runnable GLTFLoader code for Draco, Meshopt and KTX2, and decoder troubleshooting.

A smaller file is only an improvement if GLTFLoader can still decode it and the model still looks right on the devices you support. Three.js can load an unusually broad set of glTF compression extensions, but several of them require extra decoder setup. The production workflow is therefore: understand the asset, create a conservative baseline, add one advanced compression feature at a time, and test the exact loader configuration that will ship.

Choose GLB or glTF before optimizing

Prefer GLB when you want one deployable file containing the scene, geometry, animation, and textures. It is harder to misplace a texture or .bin file during a deployment. Choose JSON glTF when separately cached textures or editable text are useful, but preserve every referenced file and its relative path. A lone .gltffile is not necessarily a complete model.

Inspect the model before changing it

Record the original file size, texture dimensions, triangle count, animation clips, morph targets, and material count. Open the original in your Three.js scene and capture a few representative views. Those views are your visual baseline. Texture-heavy assets benefit most from resizing and image compression; geometry-heavy assets may benefit from Draco or Meshopt; a small animated character might need very little processing at all.

Choose Compatible, Smallest, or Custom deliberately

Start with Compatible for a higher-quality web candidate. Its name does not mean decoder-free: both named presets enable Draco and use WebP textures. Configure the loader below before shipping either output.

SettingCompatibleSmallest
Texture formatWebPWebP
Maximum texture size2048 px1024 px
Texture quality9075
Draco geometry compressionOnOn
Mesh simplificationOffOff

Both presets deduplicate, prune unused data, and weld vertices; they do not flatten, join, or instance the scene. Smallest reduces texture detail more aggressively, so compare labels, normal maps, and transparency at the intended viewing distance. Geometry compression does not remove triangles.

A baseline without adding compression extensions

For an ordinary PNG/JPEG model that must load without optional decoders, select Compatible first, then change these settings. The preset becomes Custom when you edit them:

  • Set Texture format to Original to preserve source images and resolution.
  • Turn Draco off in Advanced options.
  • Leave mesh simplification, flattening, joining, and instancing off.
  • Keep deduplication, pruning, and welding enabled, then compare the result.

Original preserves existing texture extensions too: it does not turn source KTX2 or WebP into PNG. For a strict PNG/JPEG destination, explicitly convert supported source textures to PNG and validate the output. Review the output's required extensions rather than assuming any preset removes every source extension. Try the settings in OptimizeGLB, keeping the source as your visual reference.

A working Three.js loader: Draco, Meshopt, and KTX2

This standalone browser example uses Three.js 0.183.2 and Vite. It frames the model, supplies image-based lighting, plays the first animation, and reports loading errors. Create an empty project directory and run the commands below in a macOS/Linux shell. On Windows, copy the same two decoder directories with your file manager. Keep the decoder assets and JavaScript imports on the same Three.js version.

npm install --save-exact three@0.183.2
npm install --save-dev vite
mkdir -p public/decoders
cp -R node_modules/three/examples/jsm/libs/draco/gltf public/decoders/draco
cp -R node_modules/three/examples/jsm/libs/basis public/decoders/basis
# Save your optimized GLB as public/model.glb, then start the server:
npx vite

Save the next two files as index.html and main.jsin the project root. Put your downloaded GLB at public/model.glb, then open the local URL printed by Vite. Use HTTP; do not open the HTML directly with a file:// URL. This is a standalone example, not code to paste into a React component.

index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Optimized GLB in Three.js</title>
    <style>
      body { margin: 0; font: 16px system-ui; background: #18202b; color: white; }
      canvas { display: block; width: 100vw; height: 100vh; }
      #status { position: fixed; top: 1rem; left: 1rem; max-width: 90vw; }
    </style>
  </head>
  <body>
    <p id="status" role="status">Loading model…</p>
    <canvas id="viewer" aria-label="3D model preview"></canvas>
    <script type="module" src="/main.js"></script>
  </body>
</html>

main.js

import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';
import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';

const status = document.querySelector('#status');
const renderer = new THREE.WebGLRenderer({
  canvas: document.querySelector('#viewer'), antialias: true,
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.toneMapping = THREE.ACESFilmicToneMapping;
const scene = new THREE.Scene();
scene.background = new THREE.Color('#18202b');
const room = new RoomEnvironment();
const pmrem = new THREE.PMREMGenerator(renderer);
const environment = pmrem.fromScene(room);
scene.environment = environment.texture;
room.dispose();
pmrem.dispose();
const camera = new THREE.PerspectiveCamera(45, 1, 0.01, 1000);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;

// Paths are served from public/; use files from the same installed Three.js version.
const draco = new DRACOLoader().setDecoderPath('/decoders/draco/');
const ktx2 = new KTX2Loader().setTranscoderPath('/decoders/basis/');
ktx2.detectSupport(renderer); // Must run before loading KTX2 textures.
const loader = new GLTFLoader();
loader.setDRACOLoader(draco);
loader.setKTX2Loader(ktx2);
loader.setMeshoptDecoder(MeshoptDecoder);

function resize() {
  renderer.setSize(window.innerWidth, window.innerHeight);
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
}
window.addEventListener('resize', resize);
resize();

let mixer;
let previousTime = performance.now();
renderer.setAnimationLoop((time) => {
  const delta = Math.min(Math.max((time - previousTime) / 1000, 0), 0.1);
  previousTime = time;
  mixer?.update(delta);
  controls.update();
  renderer.render(scene, camera);
});

try {
  const started = performance.now();
  const gltf = await loader.loadAsync('/model.glb');
  scene.add(gltf.scene);
  const bounds = new THREE.Box3().setFromObject(gltf.scene);
  if (!bounds.isEmpty()) {
    const sphere = bounds.getBoundingSphere(new THREE.Sphere());
    const radius = Math.max(sphere.radius, 0.01);
    const verticalFov = THREE.MathUtils.degToRad(camera.fov);
    const horizontalFov = 2 * Math.atan(Math.tan(verticalFov / 2) * camera.aspect);
    const distance = radius / Math.sin(Math.min(verticalFov, horizontalFov) / 2) * 1.2;
    controls.target.copy(sphere.center);
    camera.position.copy(sphere.center).add(new THREE.Vector3(1, 0.6, 1).normalize().multiplyScalar(distance));
    camera.near = Math.max(radius / 1000, 0.001);
    camera.far = distance + radius * 10;
    camera.updateProjectionMatrix();
    controls.update();
  }
  if (gltf.animations.length) {
    mixer = new THREE.AnimationMixer(gltf.scene);
    mixer.clipAction(gltf.animations[0]).play(); // Test other clips individually.
  }
  renderer.render(scene, camera);
  status.textContent = 'Model ready (' + Math.round(performance.now() - started) + ' ms to load and render). Drag to orbit.';
} catch (error) {
  status.textContent = 'Model failed to load. Check the model URL and decoder requests in DevTools.';
  console.error(error);
}

window.addEventListener('pagehide', (event) => {
  if (event.persisted) return; // Keep the viewer usable after back/forward restoration.
  renderer.setAnimationLoop(null);
  draco.dispose();
  ktx2.dispose();
  controls.dispose();
  environment.dispose();
  renderer.dispose();
});

Compatible and Smallest need the Draco loader; their WebP textures do not need KTX2 transcoding. Choose KTX2 explicitly in Custom when you want Basis textures, then keep setKTX2Loader and detectSupport(renderer). The Meshopt decoder handles files compressed with Meshopt by other tools. OptimizeGLB's mesh simplification uses meshoptimizer, but that is not the same as exporting Meshopt compression.

Fix the common loader failures

  • No DRACOLoader instance provided: call setDRACOLoader before loadAsync.
  • setMeshoptDecoder must be called: import and attach MeshoptDecoder before loading the asset.
  • Missing KTX2 support: attach KTX2Loader and call detectSupport with the renderer you use to display the model.
  • Decoder 404 or unexpected HTML: inspect Network requests. The Draco directory needs draco_wasm_wrapper.js, draco_decoder.wasm, and draco_decoder.js. The Basis directory needs basis_transcoder.js and basis_transcoder.wasm. Do not substitute OptimizeGLB's Node decoder wrappers or KTX2 encoder files for these browser decoder files.
  • Worker, WASM, or CORS errors: check your host's response headers and Content Security Policy. Self-host the decoder files; allow the workers and WebAssembly your loaders require.

WebP does not need a WASM decoder in current browsers, but it is still a glTF extension decision. If the same asset must also open in an engine, editor, marketplace, or older embedded webview, validate that destination before making WebP the only texture source.

Do not confuse download size with render cost

Draco can substantially reduce network transfer while adding decode work. It does not automatically lower draw calls, texture memory, or the number of triangles rendered after decoding. Texture dimensions, material count, duplicated meshes, overdraw, and scene structure still matter. Measure download time, decode time, peak memory, and frame rate separately on a representative mobile device.

The example's time-to-ready includes fetching, decoding, and the first render; it is not a pure decoder benchmark. Compare original and optimized files under the same viewport and network conditions. Record file bytes, cold-load time with the cache disabled, warm-load time, frame rate while orbiting, and visible differences. Do not infer GPU memory savings from a smaller WebP download; decoded texture dimensions still matter.

Handle external resources deliberately

For a .gltf model, serve its sidecars from the same relative layout used by the JSON. Filenames are case-sensitive on many production hosts. Verify MIME types, CORS headers for cross-origin assets, URL encoding for spaces, and cache invalidation. If you receive a missing buffer or texture error, fix the package rather than silently rendering an incomplete scene.

To test JSON glTF with this example, place its complete package under public/models/ and change the request to loader.loadAsync('/models/scene.gltf'). Preserve the paths referenced inside the file, including any external resources referenced by a GLB. For deployment under a URL subdirectory, change the root-relative model and decoder paths to include that base path.

Three.js release checklist

  1. Run the optimized asset through the Khronos glTF Validator.
  2. Load it with the exact production Three.js and decoder versions.
  3. Exercise every animation, morph target, camera, and material variant.
  4. Compare silhouettes, normals, transparency, and texture detail.
  5. Test a cold load and repeat load on desktop and mobile.
  6. Keep the source asset and conservative output available for rollback.

Related official resources

These links point to the maintainers' current documentation, source repositories, or validation tools rather than third-party summaries.