Skip to content

Instantly share code, notes, and snippets.

@benmann
Created January 23, 2017 14:43
Show Gist options
  • Save benmann/e71f337da0d16cc5fc5b47cf4ecf0dda to your computer and use it in GitHub Desktop.
Save benmann/e71f337da0d16cc5fc5b47cf4ecf0dda to your computer and use it in GitHub Desktop.
Lazy loading images
// HTML
<a href="#" class="lazyimage">
<div class="placeholder" data-large="fullsize.jpg">
<img src="small.jpg" class="img-small">
<div style="padding-bottom: 39.47%;"></div>
<!-- % calculated from ratio eg. 450/1140px -->
</div>
</a>
// CSS
.lazyimage {
.placeholder {
background-color: #ccc;
background-size: cover;
background-repeat: no-repeat;
position: relative;
overflow: hidden;
}
.placeholder img {
position: absolute;
opacity: 0;
top: 0;
left: 0;
width: 100%;
transition: opacity 1s linear;
}
.placeholder img.loaded {
opacity: 1;
}
.img-small {
filter: blur(50px);
transform: scale(1);
}
}
// JS
if($(".lazyimage").length) {
$(".lazyimage").each(function(index) {
var placeholder = $(this).find($(".placeholder")),
small = $(this).find($(".img-small"));
var img = new Image();
img.src = small.src;
img.onload = function () {
small.classList.add('loaded');
};
var imgLarge = new Image();
imgLarge.src = placeholder.attr("data-large");
imgLarge.onload = function () {
imgLarge.classList.add('loaded');
};
placeholder.append(imgLarge);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment