javascript – How to load images dynamically (or lazily) when users scrolls them into view-ThrowExceptions

Exception or error:

I’ve noticed this in numerous “modern” websites (e.g. facebook and google image search) where the images below the fold load only when user scrolls down the page enough to bring them inside the visible viewport region (upon view source, the page shows X number of <img> tags but they are not fetched from the server straight away). What is this technique called, how does it work and in how many browsers does it work. And is there a jQuery plugin that can achieve this behavior with minimum coding.


Bonus: can someone explain if there is a “onScrolledIntoView” or similar event for HTML elements. If not, how do these plugins work?

How to solve:

Some of the answers here are for infinite page. What Salman is asking is lazy loading of images.



EDIT: How do these plugins work?

This is a simplified explanation:

  1. Find window size and find the position of all images and their sizes
  2. If the image is not within the window size, replace it with a placeholder of same size
  3. When user scrolls down, and position of image < scroll + window height, the image is loaded


Dave Artz of AOL gave a great talk on optimization at jQuery Conference Boston last year. AOL uses a tool called Sonar for on-demand loading based on scroll position. Check the code for the particulars of how it compares scrollTop (and others) to the element offset to detect if part or all of the element is visible.

jQuery Sonar

Dave talks about Sonar in these slides. Sonar starts on slide 46, while the overall “load on demand” discussion starts on slide 33.


I came up with my own basic method which seems to work fine (so far). There’s probably a dozen things some of the popular scripts address that I haven’t thought of.

Note – This solution is fast and easy to implement but of course not great for performance. Definitely look into the new Intersection Observer as mentioned by Apoorv and explained by if performance is an issue.

The JQuery

$(window).scroll(function() {
    $.each($('img'), function() {
        if ( $(this).attr('data-src') && $(this).offset().top < ($(window).scrollTop() + $(window).height() + 100) ) {
            var source = $(this).data('src');
            $(this).attr('src', source);

Sample html code

    <img src="" data-src="pathtoyour/image1.jpg">
    <img src="" data-src="pathtoyour/image2.jpg">
    <img src="" data-src="pathtoyour/image3.jpg">


When the page is scrolled each image on the page is checked..

$(this).attr('data-src') – if the image has the attribute data-src

and how far those images are from the bottom of the window..

$(this).offset().top < ($(window).scrollTop() + $(window).height() + 100)

adjust the + 100 to whatever you like (- 100 for example)

var source = $(this).data('src'); – gets the value of data-src= aka the image url

$(this).attr('src', source); – puts that value into the src=

$(this).removeAttr('data-src'); – removes the data-src attribute (so your browser doesn’t waste resources messing with the images that have already loaded)

Adding To Existing Code

To convert your html, in an editor just search and replace src=" with src="" data-src="


There is a pretty nice infinite scroll plugin here

I’ve never programmed one myself, but I would imagine this is how it works.

  1. An event is bound to the the window scrolling

  2. The called function checks if scroll top is greater than the window size

    function myInfiniteScrollFunction() {  
        if($(window).scrollTop() == $(window).height())  
  3. An AJAX request is made, specifying which result # to start at, how many to grab, and any other parameters necessary for the data pull.

        type: "POST",
        url:  "myAjaxFile.php",
        data: {"resultNum": 30, "numPerPage": 50, "query": "interesting%20icons" },
        success: myInfiniteLoadFunction(msg)
  4. The ajax returns some (most-likely JSON formatted) content, and passes them into the loadnig function.

Hope that makes sense.


Lazy loading images by 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 IntersectionObserver to lazy load images performantly.


The Swiss Army knife of image lazy loading is YUI’s ImageLoader.

Because there is more to this problem than simply watching the scroll position.


This Link work for me demo

1.Load the jQuery loadScroll plugin after jQuery library, but before the closing body tag.

<script src=""></script><script src="jQuery.loadScroll.js"></script>

2.Add the images into your webpage using Html5 data-src attribute. You can also insert placeholders using the regular img’s src attribute.

<img data-src="1.jpg" src="Placeholder.jpg" alt="Image Alt"><img data-src="2.jpg" src="Placeholder.jpg" alt="Image Alt"><img data-src="3.jpg" src="Placeholder.jpg" alt="Image Alt">

3.Call the plugin on the img tags and specify the duration of the
fadeIn effect as your images are come into view

$('img').loadScroll(500); // in ms


Im using jQuery Lazy. It took me about 10 minutes to test out and an hour or two to add to most of the image links on one of my websites ( I have NO (none/zero) relationship of any kind to the dev, but it saved me a lot of time and basically helped improve our bounce rate for mobile users and I appreciate it.

Leave a Reply

Your email address will not be published. Required fields are marked *