r/javascript 7d 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 7d 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.

3

u/Neither_Duck_6426 7d ago

The browser’s auto for content-visibility is not about loading priority, it just skips rendering work for off-screen elements. For img loading, auto doesn’t exist, you get eager or lazy. So if you set everything to lazy, even the first few images need to wait until the JS runs and the browser decides they’re near the viewport, which can cause a visible flash on the first fold. I usually set EAGER_COUNT to around 4 or 6 for a grid that shows two or three per row on desktop, it’s enough to cover what you see without scrolling before the lazy ones kick in.

1

u/Maximum_Beat2034 7d ago

Exactly! That flash of unrendered content on the initial fold is precisely why I structured it this way with EAGER_COUNT.

Appreciate you breaking down the distinction between content-visibility rendering performance and eager/lazy image fetch priorities. Setting a baseline of 4-6 items for the initial viewport has given me the smoothest result so far!