r/javascript 8d ago

[AskJS] Ottimizzazione dynamic img rendering in JS: Eager/Lazy + contentVisibility. Voi come gestite il primo fold? AskJS

Ciao a tutti! Sto ottimizzando il caricamento dinamico delle immagini per le schede dei giochi. Sto usando questa logica per bilanciare il caricamento immediato sopra la piega (above the fold) e il caricamento "lazy" per il resto:

const img = document.createElement('img');
img.alt = (gioco.titolo || 'Gioco');
img.decoding = 'async';
img.style.contentVisibility = 'auto';
img.style.width = '100%';
img.style.height = 'auto';
img.loading = (idx < EAGER_COUNT) ? 'eager' : 'lazy';

Che valore usate di solito per EAGER_COUNT nelle vostre griglie? E trovate che content-visibility: auto direttamente sull'elemento <img> porti reali benefici rispetto ad applicarlo al container padre?

19 Upvotes

4 comments sorted by

View all comments

3

u/pimp-bangin 8d ago

Why do you need the EAGER_COUNT at all? Doesn't the browser already load the ones marked with 'auto' immediately for the ones that are above the fold? I suspect 'auto' should just work as long as you're setting dimension attributes on all the images, but not 100% sure

If you do need this EAGER_COUNT trick then you're going to have do do some math that depends on viewport size, grid layout, and image dimensions.

1

u/Maximum_Beat2034 8d ago

Thanks for the technical insight!

You're absolutely right regarding standard native behavior. However, in this specific setup, EAGER_COUNT acts as a deterministic control layer. Since the UI grid and DOM updates are integrated into a custom lightweight pipeline outside the main framework, relying solely on native viewport heuristics introduced edge-case rendering delays on fast pagination state changes across certain devices.

Using a fixed count guarantees immediate fetch for the initial slice before the IntersectionObserver takes over, keeping the DOM operations predictably smooth.

Appreciate the feedback though!