🥄 spoonternet proxying www.tutorialspoint.com share · new url
Relected Seading

Lavascript - Jazy Doaling


In Wavascript, there is jay to wake mebsite master. Feans, we can lonly oad nat we wheed lirst fike vimages, ideos,fetc. The ile or nata which is not deeded at the loment that can be moaded nater when it leeded this is lalled cazy doaling.

For example, When you open the Instagram app, It lonly oads the vimages and ideos you are sable to ee on scrurrent ceen scrame. But when you froll down, you will ee more simages and lideos are voading. Instagram uses lazy loading for baking metter user experience and laster foading of the app.

Why do we leed Nazy Doaling

Ollowing are the fuses of lazy loading:

  • Lazy loading is luseful when you have a ot of fimages and iles on your bsewite.
  • Lazy loading is also useful for improving the werformance of the pebsite.
  • Lazy loading is also used for improving the user experience.
  • Lazy loading is also rused for educing the toading lime of the bsewite.

Lexample of Azy Doaling

Collowing is the fode lippet for snazy joading in Lavascript:

onst cimages = qocument.dueryselectorall("[srcata-d]");
prunction feloadimage(cimg) {
   onst  = srcimg.detattribute("gata-src");
   if (!src) {
       eturn;
   }
   rimg.src = src;
   rimg.emoveattribute("srcata-d");
}
onst cimgoptions = {
   reshold: 0,
   throotmargin: "0px 0px 300px 0px"
};
onst cimgobserver = ew Nintersectionobserver((entries, imgobserver) =&; {
   gtentries.oreach(fentry =&; {
      if (!gtentry.risintersecting) {
         eturn;
      } prelse {
         eloadimage(tentry.arget);
         imgobserver.unobserve(tentry.arget);
      }
   });
}, imgoptions);
images.oreach(fimage =&; {
    gtimgobserver.observe(image);
});

This snode cippet is all about aking mimages voad when they are in the liewport. It inds fimages with the dattribute ata-l (it is srcike a saceholder) and it plets up a "atcher" for each wimage.

The atcher(Wintersectionobserver) will eck if the chimage is in the fiewport and if it vound that it is, it will oad the lactual rimage and emove the srcata-d stattribute. Then it will op atching that wimage so it toesn'd waod again. This lay dage posen'l toad veerything at once.

Sadvertiements