Created
June 26, 2013 19:49
-
-
Save stinoga/5870990 to your computer and use it in GitHub Desktop.
Lazy Loading Images based on adjacent section headers. Dependencies: JQuery, Lo-Dash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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