Skip to content

Instantly share code, notes, and snippets.

@stinoga
Created June 26, 2013 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stinoga/5870990 to your computer and use it in GitHub Desktop.
Save stinoga/5870990 to your computer and use it in GitHub Desktop.
Lazy Loading Images based on adjacent section headers. Dependencies: JQuery, Lo-Dash
// Defer Image loading until parent headers come into view
// =======================================================
// Setup vars
var win = $(window),
lazyScrollDelta = 200,
headerIndex = 0,
sectionCount = all_products.length - 1;
// Bind scroll event
// We'll use lodash to throttle this function, to keep down the js calls
win.scroll( _.throttle( function() {
console.log(headerIndex);
// Vars for our scroll target, and each header's offset from the top of the window
var scrollTarget = win.scrollTop() + win.height() + lazyScrollDelta,
headerOffset = $('#header' + headerIndex).offset().top;
// If our header offset goes past our scroll target, let's load some images
if (scrollTarget >= headerOffset) {
// Set the Image Source
// --------------------
console.log('Scroll is ' + scrollTarget + ': Header is ' + headerOffset);
console.log('setting source');
var dataSrc = $('#product_list' + headerIndex + ' .grid_image');
$.each(dataSrc, function(index, product) {
var prod = $(product);
$(product).attr('src', prod.data('src'));
});
// make sure we aren't counting too high with our header index
if (headerIndex < sectionCount) {
headerIndex++;
}
}
}, 100));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment