Show image when in viewpoint of browser window I am working on a web project and am trying to create a way to detect when an image is in viewpoint of the browser window then load/show the image. Since there are some rather large image that are being resize to use a thumbnails, I am trying to take into consideration those that might view it one a mobile device and reduce page loading time. I notice that many site with galleries are doing the same thing.

I create a little script using JavaScript to detect when an &lt;img /&gt; tag is in view and then take its data attribute value (the URL of the image) and set it's &lt;img src=""/&gt; attribute to it.

Is this is an efficient way of doing it or should I just use PHP the create thumbnails?

I have included snippets of the HTML and JavaScript I am using.

HTML of the image

&lt;img data-image-src="images/c9c191f226c643eabcce6debfe76049d.png" src="" alt="A nify Image" /&gt;


JavaScript with jQuery

//Show images when in viewpoint
$(window).on('scroll load',function(){
    //Window width &amp; height
    var viewpointWidth = $(window).width(),
    viewpointHeight = $(window).height(),
    //Document Top pos &amp; Left pos
    documentScrollTop = $(document).scrollTop(),
    documentScrollLeft = $(document).scrollLeft(),
    //Document Positions
    minTop = documentScrollTop,
    maxTop = documentScrollTop + viewpointHeight,
    minLeft = documentScrollLeft,
    maxLeft = documentScrollLeft + viewpointWidth;
    //Loop for each image
    $('.page-content img').each(function(){
        $eleImage = $(this),
        elementOffset = $eleImage.offset();       
        if((elementOffset.top &gt; minTop &amp;&amp; elementOffset.top &lt; maxTop) &amp;&amp; (elementOffset.left &gt; minLeft &amp;&amp;elementOffset.left &lt; maxLeft)) {
            $(this).attr('src',$(this).data('image-src'));
        }
    });
});
Correctness


You need to handle resize events also. Yes, you can add it like : $(window).on('scroll load resize', ...
You are only checking for the visibility of the top/left corner, if you load a large image, scroll right, and then scroll down, you will see the right edges of the ALT text of the images, but because their top/left corner is not in viewport, those images will not load. You might want to check if any point of the img box is visible.


Browser Behavior


Make sure you have &lt;!DOCTYPE HTML&gt; on your document, this will load all images if you miss doctype declaration. (for Firefox, Chrome, don't know about others)
You might want to mark images processed, by adding a class or another data; and do not fiddle with the src attributes of the images once they are loaded.


Javascript related


Because you miss a var before $eleImage and elementOffset, they pollute global namespace.
You copy the value of $(this) here : $eleImage = $(this), but you keep using $(this) below.