Created
January 23, 2017 14:43
-
-
Save benmann/e71f337da0d16cc5fc5b47cf4ecf0dda to your computer and use it in GitHub Desktop.
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
// 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