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 <img />
tag is in view and then take its data attribute value (the URL of the image) and set it's <img src=""/>
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
<img data-image-src="images/c9c191f226c643eabcce6debfe76049d.png" src="" alt="A nify Image" />
JavaScript with jQuery
//Show images when in viewpoint
$(window).on('scroll load',function(){
//Window width & height
var viewpointWidth = $(window).width(),
viewpointHeight = $(window).height(),
//Document Top pos & 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 > minTop && elementOffset.top < maxTop) && (elementOffset.left > minLeft &&elementOffset.left < maxLeft)) {
$(this).attr('src',$(this).data('image-src'));
}
});
});
onresize
even to jQuery's.on()
even handler like so$(window).on('scroll load resize',function(){...}
or go about it a different way? \$\endgroup\$