Images Lazy Loading

From WikiMLT

IMG tag now sup­ports Lazy load­ing and more

Figure 1. Tip: <img> sup­ports lazy-load­ing, async de­cod­ing and much more.

This sec­tion and the im­age are bor­rowed from the Ad­dy Osmani's post at LinkedIn.

Tip: <img> sup­ports lazy-load­ing, async de­cod­ing and much more. Learn about them in my post for Stack Over­flow: Pic­ture per­fect im­ages with the mod­ern <img> el­e­ment.

A few more re­cent posts on <img> you might ap­pre­ci­ate:

Back­ground im­ages Lazy load­ing

This sec­tion is based on the ar­ti­cle Lazy Load­ing Im­ages – The Com­plete Guide pro­vid­ed by Rahul Nan­wani at imagekit​.io.

With CSS back­ground im­ages it is not that straight­for­ward. To load CSS back­ground im­ages, the brows­er needs to build the DOM (Doc­u­ment Ob­ject Mod­el) tree, as well as the CS­SOM (CSS Ob­ject Mod­el) tree, to de­cide if the CSS style ap­plies to a DOM node in the cur­rent doc­u­ment.

If the CSS rule spec­i­fy­ing the back­ground im­age does not ap­ply to an el­e­ment in the doc­u­ment, then the brows­er does not load the back­ground im­age. If the CSS rule is ap­plic­a­ble to an el­e­ment in the cur­rent doc­u­ment, then the brows­er loads the im­age.

This may seem com­plex at first, but this same be­hav­ior forms the ba­sis of the tech­nique for lazy load­ing back­ground im­ages. In sim­ple terms, we trick the brows­er in­to not ap­ply­ing the back­ground im­age CSS prop­er­ty to an el­e­ment till that el­e­ment comes in­to the view­port.

An im­ple­men­ta­tion of the ap­proach il­lus­trat­ed by Rahul Nan­wani at codepen​.io could be found in the script: Me­di­aWi­ki: Gad­get – Tem­plate Con­tent Ar­ti­cle Header.js.

More ref­er­ences