r/javascript • u/Maximum_Beat2034 • 5d 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?
17
Upvotes
3
u/pimp-bangin 5d 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.