You could check the lazy load plugin, but if you prefer to do it by yourself, then you could do it by adding a CSS class when you reach the image position.
To do it you can base you solution on this topic and do something like:
function isElementInViewport(el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */ );
}
var yourImage = $('#yourImage').get(0);
if(isElementInViewport(yourImage){
$('#yourImage').addClass('loadImage');
}
And then in your CSS you just have to do add the background only when the loadImage
class is added:
#yourImage{
...
}
#yourImage.loadImage{
background: url(path/to/yourImage.jpg) no-repeat center;
}