Why my three js code is working slow in lighthouse and on mobile phone?

Hello! Can you please tell me, how can i optimize my THREE JS code? I have perfomance about 60 in LightHouse. I want to async load all 3 models in only one scene and add it to 3 div elements. I guess it can optimize loading and web page, but may be there is other ways to optimize this code?


import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.module.js';
// import {FBXLoader} from 'https://cdn.jsdelivr.net/npm/three@0.118.1/examples/jsm/loaders/FBXLoader.js';
// import { OrbitControls } from "https://threejs.org/examples/jsm/controls/OrbitControls.js";
import { GLTFLoader } from 'https://threejs.org/examples/jsm/loaders/GLTFLoader.js';

const container = document.querySelector("#canvas");
const container2 = document.querySelector(".number2");
const container3 = document.querySelector(".number3");

const addObject = (container, modelpath, lightIntensity) => {
	const scene = new THREE.Scene();
	const camera = new THREE.PerspectiveCamera( 75, container.offsetWidth / container.offsetHeight, 0.1, 1000 );
	const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true  });
	const light = new THREE.AmbientLight();
	light.intensity = lightIntensity

	renderer.setPixelRatio( container.devicePixelRatio );
	renderer.setSize( container.offsetWidth, container.offsetHeight );
	container.appendChild( renderer.domElement );
	// const controls = new OrbitControls( camera, renderer.domElement );

	scene.add( light );

	const loader = new GLTFLoader();

	loader.load(modelpath, function( gltf ) {
		const model = gltf.scene;

		model.material = new THREE.MeshLambertMaterial({
			color: 0xff0000,
			side: THREE.DoubleSide
		camera.position.z = 5

		function animate() {
			requestAnimationFrame( animate );
			// controls.update();
			// model.rotation.x += 0.01;
			model.rotation.y += 0.001;
			renderer.render( scene, camera );


addObject(container, '3dmodel/scene.gltf', 3);
addObject(container2, 'meat/scene.gltf', 3);
addObject(container3, 'tushenka/scene.gltf', 4);

By the way, when post moderating, i found solution: i just deincreased textures of 3d objects from 2k to 256 x 256, and my pefromance increased to 96. Thats amazing. But i still want to find any code optimaztion methods.

It’s not recommended to create multiple instances of WebGLRenderer if you need to render to different views. Also having multiple animation loops is not good.

I suggest you use the following example as a code template. It also renders to multiple views but reuses the renderer (and the canvas!): three.js webgl - multiple elements

Alternatively, if you need more flexibility you can also use a single canvas per view. This is demonstrated in: three.js webgl - multiple canvases - grid

1 Like

Thank you so much!

1 Like