How lazy loading images using JavaScript works?
Asked Answered
F

9

15

I am curious about how lazy loading images, images that will be loaded when scrolled to them, works.

Any hint?

Footcloth answered 12/3, 2012 at 13:10 Comment(1)
Does this answer your question? How do you make images load only when they are in the viewport?Prewitt
F
18

Here's a how-to, using plugins: http://www.webresourcesdepot.com/lazy-loading-of-images-resources-you-need/ here's the jquery plugin: http://www.appelsiini.net/projects/lazyload

basically you put a dummy image in your src attribute and add another attribute for the actual image, JS detects the scroll position of the page, and loads the image data once you get close enough to the image. it does that by replacing the src with the source of the actual image.

here's another explanation: http://engineering.slideshare.net/2011/03/faster-page-loads-with-image-lazy-loading/

Festive answered 12/3, 2012 at 13:12 Comment(0)
B
10

Solution for 2020+:

There is a native way to lazy load images that already works in some browsers. While standardization is still underway, you can already use it today! Just add the loading attribute to your image tags and set it to "lazy":

<img
    src="picture.jpg"
    width="100"
    height="100"
    alt="descriptive text"
    loading="lazy"
>

And that's it. Compatible browsers will load that image lazily as soon as the current viewport is close enough.

Further information available here:

If you need a solution for older browsers, you should have a look at Lazy loading on MDN.

Brachylogy answered 23/1, 2020 at 14:55 Comment(3)
Is there any downside to lazy loading like this? If not, shouldn't every image use the loading attribute?Moynahan
#61315250Brachylogy
This solution currently does not support printing in chrome, see this bugreport. When you print a page, the images that have not yet been loaded, will be missing in the printout.Ariew
W
6

And example on how to do this, easily.

<img src="/images/lazy.jpg" data-real-src="/images/company-1.jpg">

The "lazy.jpg" can be used on all images, which will result in really just one image is loaded (and it's a 1x1px small weight image). So, consider I'm having a list of 250 stores to visit, with a company logo for each. Could look like this:

<img src="/images/lazy.jpg" data-real-src="/images/company-1.jpg">
<img src="/images/lazy.jpg" data-real-src="/images/company-2.jpg">
<img src="/images/lazy.jpg" data-real-src="/images/company-3.jpg">
...

Then comes the magic! Put this in your javascript file:

$('img[src="/images/lazy.jpg"]').each(function(index, el) {
    $(el).attr('src', $(el).data('real-src'));
});

And wacka-wacka, all the lazy.jpg images will be replaced by their "real" images. The purpose getting your html page loading faster (since those 250 companies all have the same "logo" in lazy.jpg :) ... But the JS takes care of it all after DOM finished loaded.

This is a jQuery solution of course. Can be done with pure js, as well.

Wakeless answered 19/2, 2016 at 13:0 Comment(0)
N
3

Browser-level native lazy-loading is finally available.

<img src="image.png" loading="lazy" alt="…" width="200" height="200">

<img loading=lazy> is supported by most popular Chromium-powered browsers (Chrome, Edge, Opera), Firefox and the implementation for WebKit (Safari) are in progress. Can I use has detailed information on cross-browser support. Browsers that do not support the loading attribute simply ignore it without side-effects.

Improved data-savings and distance-from-viewport thresholds

Nationalism answered 23/7, 2020 at 19:30 Comment(0)
W
2

You can use justlazy, which is independent of dependencies like jQuery and very lightweight:

The only call you need is:

var placeholders = document.querySelectorAll(".load-if-visible");
for (var i = 0; i < placeholders.length; ++i) {
  Justlazy.registerLazyLoad(placeholders[i]);
}

The placeholders have to be the following structure:

<span data-src="url/to/image" data-alt="some alt text"
      data-title="some title" class="load-if-visible">
</span>

For SEO reasons you can use any other placeholder (e.g. placeholder image).

Additionally there is a guide how to use it and some general things about lazy loading of images.

Wyant answered 17/7, 2015 at 14:40 Comment(0)
R
2

Lazy loading images using conventional way of attaching listener to scroll events or by making use of setInterval is highly non-performant as each call to getBoundingClientRect() forces the browser to re-layout the entire page and will introduce considerable jank to your website.

Use Lozad.js (just 569 bytes with no dependencies), which uses InteractionObserver to lazy load images performantly.

Rendarender answered 29/8, 2017 at 18:42 Comment(1)
Lozad seems promising, thank you.Demur
O
1

2021 - keep it simple...

Lots of plugin recommendations here, and depending on your use case those may be valuable to you.

If you can't be bothered to write this short snippet of code below, or you need callbacks already built out then you can use this plugin I built which is based on this exact answer and only 0.5kb when minified. My plugin, Simply Lazy, can even work with IE if you simply add a polyfill.

At the end of the day if you just need to lazy load some images then it's as simple as:

<img data-src="your-image-path-here" class="lazyload" />

And:

let observer = new IntersectionObserver((entries, observer) => {
  entries.forEach(function (entry) {
    if (entry.intersectionRatio > 0 || entry.isIntersecting) {
      const image = entry.target;
      observer.unobserve(image);

      if (image.hasAttribute('src')) {
        // Image has been loaded already
        return;
      }

      // Image has not been loaded so load it
      const sourceUrl = image.getAttribute('data-src');
      image.setAttribute('src', sourceUrl);

      image.onload = () => {
        // Do stuff
      }

      // Removing the observer
      observer.unobserve(image);
    }
  });
});

document.querySelectorAll('.lazyload').forEach((el) => {
  observer.observe(el);
});

Using the Intersection Observer API makes this all very simple. You can also use it within the shadowRoot and it works fine there as well.

I've also found this article helpful to understand what is going on here.

Ottoman answered 11/12, 2020 at 20:42 Comment(0)
A
0

There's many ways to implement lazy loading. The process is just that you load what you need. You can lazy load anything in the software scene. On websites most use it when loading in images and it's because most of the website is pretty much just images. I mean the artwork of the website plus the actual persons pictures they could have thousands of images on your server. This normally causes a slow down when you try and load all of them at the same time. At some point it starts to slow down the process. So, lazy loading is normally done for large websites. Like I said you can do this numerous ways. one way was already given. Have the img tag already loaded but the src part points to a dummy file something that is small in size. Don't use a image that is graphic or a picture... use something like a grey block.. or could use nothing. Then when the scroll part is near the scrolling point where the images are close by. It will run a function where it will replace the src with the real image link. Another way is to use ajax and the scroll point when close will append... load in the actual html code with the image in the src. This is what I actually use. I write a PHP file to lazy load images, data, text.

The whole point of this method is to download the files from a website when needed. When a image is loaded it's actually being downloaded from your server. So, the downloading process plus the actual loading time can increase when you start dealing with larger image files and too many of them.

Aloysius answered 22/2, 2015 at 17:16 Comment(0)
Z
0

Here is a demo example project: Live Demo

You can try implementing lazy loading images with JavaScript by using small blurry placeholder images that display until the full image is downloaded.

<div class="blurred-img" style="background-image: url(imageName-small.jpg)">
  <img src="imageName-original.jpg" loading="lazy" />
</div>

To create a blurry placeholder image, generate a super low-resolution version of the original image using automated tools like ffmpeg, simply execute the provided code on the command line in the target image's directory.

ffmpeg -i imageName.jpg -vf scale=20:-1 imageName-small.jpg
Zoe answered 31/7, 2023 at 16:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.