Skip to content

Commit e01f9b8

Browse files
committed
perf: Optimize carousel animation for mobile
Refactored the checkPos function that calculates the 3D scroll effect. The new implementation filters out off-screen elements and only performs expensive calculations (like getBoundingClientRect) for visible items. This drastically reduces CPU load during scrolling, fixing performance issues and janky animations on mobile devices while preserving the real-time visual effect.
1 parent 6aa83ac commit e01f9b8

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

assets/js/carousel.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,15 @@ const setCarousel = (scroller) => {
8787
const offsetWidth = target.offsetWidth;
8888

8989
const checkPos = () => {
90-
[...target.children].map(e => {
91-
const toCenter = Math.abs(window.outerWidth / 2 - e.getBoundingClientRect().left - e.getBoundingClientRect().width / 2);
92-
const toCenter2 = window.outerWidth / 2 - e.getBoundingClientRect().left - e.getBoundingClientRect().width / 2;
90+
[...target.children].forEach(e => {
91+
const childRect = e.getBoundingClientRect();
92+
// Optimization: Only process elements currently visible on screen.
93+
if (childRect.right < 0 || childRect.left > window.innerWidth) {
94+
return; // Skip heavy calculations for off-screen elements
95+
}
96+
97+
const toCenter = Math.abs(window.innerWidth / 2 - childRect.left - childRect.width / 2);
98+
const toCenter2 = window.innerWidth / 2 - childRect.left - childRect.width / 2;
9399
const viewport = toCenter / offsetWidth * 100;
94100
const viewport2 = toCenter2 / offsetWidth * 100;
95101
e.style.setProperty('--viewport', viewport);

0 commit comments

Comments
 (0)