Created
July 16, 2015 20:47
-
-
Save josephbergdoll/4ab72c3da2c5f5351db0 to your computer and use it in GitHub Desktop.
For lazy loading images
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
// Assumes all of your images are wrapped in a container with the class .js-image-container | |
// I use separate "js-" prepended classes so that way interactivity couplings are separate from | |
// visual style changes. => https://coderwall.com/p/qktuzw/decouple-javascript-classes-from-css-ones-by-using-prefix | |
// | |
// this is written with the notion that you are using markup as follows: | |
// <div class="img-container js-img-container"> | |
// <img src="../path/to/image.jpeg" data-width="[width of jpeg without px]" data-height="[height of jpeg without px]"> | |
// </div> | |
// somewhere in your CSS, you want the following: | |
// .img-container { | |
// height: 0; | |
// img { | |
// height: 0; | |
// max-width: 100%; | |
// display: block; | |
// margin: 0; | |
// opacity: 0; | |
// transition: opacity 400ms ease-out; | |
// } | |
// &.lazy-loaded { | |
// height: auto; | |
// img { | |
// opacity: 1; | |
// } | |
// } | |
// } | |
// Tell the container to take a padding-bottom equivalent to the aspect ratio of the image within it, to act as a placeholder | |
$('.js-image-container').each(function() { | |
var | |
$this = $(this), | |
$image = $this.find('img'), | |
imgWidth = $image.attr('data-width'), | |
imgHeight = $image.attr('data-height'), | |
imgAspectRatio = imgHeight / imgWidth, | |
pct = (imgAspectRatio*100).toFixed(1) + "%"; | |
$this.css('padding-bottom', pct); | |
}); | |
// Set how far from the bottom of the page you want image to start loading | |
var heightThreshold = 500; | |
// Tell unveil to watch these, and load them lazily | |
$('.js-img-container > img').unveil(heightThreshold, funtion() { | |
// when it's loaded… | |
$(this).load(function() { | |
// get rid of the padding-bottom we had before as a placeholder | |
$(this).parent().removeAttr('style').addClass('lazy-loaded'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment