JavaScript
Article
By Tim Evko

Watch: Loading Images the Lazy Loading Way

By Tim Evko

Writing JavaScript can be a fun and challenging experience. Improving the performance of your website can also be an equally rewarding. You may have noticed that images on websites can be heavy and slow, but they don’t need to effect our initial page rendering. In this screencast we’ll take a look at how to best lazyload an image to speed up the performance of your site.

you can find this demo on CodePen.

--ADVERTISEMENT--

Loading the player…

  • Great article, thanks for share it!

    • This is something very interesting that is worth paying your extreme attention ,a very good chance to work for those people who want to use their free time so that they can make some extra money using their computers… I have been working on this for last two and half years and I am earning 60-90 dollar/ hour … In the past week I have earned 13,70 dollars for almost 20 hours sitting ….

      Any special qualification, degree or skills is not necessary for this, just keyboard typing and a good working and reliable internet connection ….

      Not any Time limitations to start work … You may do this work at any time when you willing to do it ….

      Just know how I have been doing this…..….see this (webiste-Iink) on my !profile!` to know how I am working` on this`

      @ 8k

  • Christine Akins

    Here is something to pay attention , a great opportunity for work for those who want to use their free time to make money using their computers… I have been doing this since last two years and I am making 40 to 70 dollars per hour … In the last week I have made 12,245 for almost 18 hours sitting ….

    ?There are no special skills required just basic typing and an internet connection ….

    ?There are no time constraints … You may do this any time when you are free ….

    ?Here is what I’ve been doing….

    < ->>w­w­w­.­y­o­u­c­a­n­a­l­s­o­c­h­a­n­g­e­y­o­u­r­f­a­t­e­l­i­k­e­o­t­h­e­r­s­a­r­e­.­b­l­o­g­s­p­o­t­.­c­o­m >

    FYTj

  • Practicous

    Very helpful article thank you ! I have a question : if the image is the first thing in the page above all paragraphs, it won’t show up even if its already in the viewport unless you scroll. How would you go about handling that case scenario?

    • Tim

      Great question! In that case, you would want to add a ‘load’ event listener like so:

      var loadImageOnScrollIntoView = function(img) {

      var imgPos = img.getBoundingClientRect(),

      src = img.getAttribute(‘data-src’);

      window.addEventListener(‘scroll’, function loadImgWhenVisible() {

      return window.scrollY >= (imgPos.top – window.innerHeight) ? (img.src = src, window.removeEventListener(‘scroll’, loadImgWhenVisible)) : false;

      });

      window.addEventListener(‘load’, function loadImgWhenVisible() {

      if (window.scrollY >= (imgPos.top – window.innerHeight)) {

      img.src = src;

      }

      window.removeEventListener(‘load’, loadImgWhenVisible);

      });

      };

      • Practicous

        Works like a charm ! Thank you Tim.
        Keep up the good work ;)

      • Alexis Reina

        I guess that in that case you could just avoid using lazy loading for that img and go with a standart src attribute :)

  • M. Rudd

    Great tutorial, very well explained, I have a couple of questions:

    First off, the last bit with apply() isn’t necessary if we’re using jquery, correct?(also, would it be wrong to do this entirely in jquery in your opinion? how much would it really affect the performance for something like this?)

    2nd: I’ve noticed in some cases(usually when the connection isn’t that fast and the images are large), the images would start to load only after the client has scrolled passed them and in some cases they won’t even notice there was an image in there, so what is the best way of implementing some sort of indicator/placeholder that indicates there is an image here and it may take a second to load so the clients don’t get passed it?

    • Roman

      For #2 I’d try this:

      – start loading the image into a JS object;
      – display a loading indicator in place of the image;
      – when loading is complete, set src attribute of the image to the data-src value.

    • Tim

      Using jQuery may very well do a lot to harm your scroll performance, since jQuery can be very slow performance wise. In a function like this, when the code needs to run on scroll, it’s important to keep the code as fast and light as possible.

      It’s possible to add an offset to this function: return window.scrollY + OFFSET >= (imgPos.top – window.innerHeight). The other option is to add a src attribute, but put a solid color placeholder or low quality image in.

  • Alexis Reina

    Hi Tim,

    Let me share some of my thoughts, though. I would not use a querySelector for all the image tags, and would use a css className like .js-lazy-img or anything like it really. IMO is a better approach, cause things can get messy very quick when there’re other plugins and libraries in place.

    Another thing is the last statement. I’ve never seen using ‘Array.apply’ like that before, I’m not saying it’s wrong, but I would take the same approach taken to convert the function arguments into a JS Array Object:

    [].slice.call(document.querySelectorAll(‘.js-lazy-img’)).forEach( … )

    You could also use apply instead, but a IMO helps a bit to understand the last bit better cause is a pretty standard way used by many libraries and plugins out there.

    One last thing. Have you tried or at least considered taking this same approach with the srcset element?

    Great video tut, thanks for sharing!

    • Tim

      Hey Alexis, thanks for commenting! A class name is a good option, and it’s what I currently use for large projects. For this demo however, it wasn’t necessary to use a class, since there are only two images on the page, and no other libraries or 3rd party code.

      The [].slice method works, but Array.apply method is better since it avoids most, if not all, of the points raised in this article: http://toddmotto.com/ditch-the-array-foreach-call-nodelist-hack/

      On all of the large projects I’m currently working on, I use the same method for lazyloading the srcset attribute on the image if it exists. So far it works very well and I haven’t ran into any issues.

      • Alexis Reina

        I didn’t know about todd motto’s article, thanks for sharing! :) I’ll definitely check your Array.apply method again. Thanks!

  • Zoran Vitez

    Great article, thanks! :D
    Have you thought about including a fallback in case js isn’t enabled?

    • Tim

      Thanks for watching! In this case the fallback would be leaving the src attribute in the image, and attaching a low res image to it. Also, alt text helps too!

Recommended
Sponsors
Get the latest in JavaScript, once a week, for free.