Created
November 3, 2014 21:19
-
-
Save zanonnicola/9e285cd78d87a34f66c8 to your computer and use it in GitHub Desktop.
Simple responsive image solution.
The idea is to add the information about different image sizes to the HTML as data attributes in a noscript tag. The content of the noscript tag would be an img tag and would be shown to browsers that have JavaScript turned off.
This file contains hidden or 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
<style> | |
.img-container { | |
position: relative; | |
padding-bottom: 56.25%; /* 16:9 ratio */ | |
height: 0; | |
overflow: hidden; | |
} | |
.img-container img { | |
position: absolute; | |
top: 0; | |
left: 0; | |
width: 100%; | |
height: 100%; | |
} | |
</style> | |
<noscript data-src-small="img-small.jpg" | |
data-src-medium="img-medium.jpg" | |
data-src-high="img-high" | |
data-src-x-high="img-x-high.jpg"> | |
<img src="img-small.jpg"> | |
</noscript> | |
<script> | |
var lazyloadImage = function (imageContainer) { | |
var imageVersion = getImageVersion(); | |
if (!imageContainer || !imageContainer.children) { | |
return; | |
} | |
var img = imageContainer.children[0]; | |
if (img) { | |
var imgSRC = img.getAttribute("data-src-" + imageVersion); | |
var altTxt = img.getAttribute("data-alt"); | |
if (imgSRC) { | |
var imageElement = new Image(); | |
imageElement.src = imgSRC; | |
imageElement.setAttribute("alt", altTxt ? altTxt : ""); | |
imageContainer.appendChild(imageElement); | |
imageContainer.removeChild(imageContainer.children[0]); | |
} | |
} | |
}, | |
lazyLoadedImages = document.getElementsByClassName("lazy-load"); | |
for (var i = 0; i < lazyLoadedImages.length; i++) { | |
lazyloadImage(lazyLoadedImages[i]); | |
} | |
var getImageVersion = function() { | |
var devicePixelRatio = getDevicePixelRatio(); /* Function defined elsewhere.*/ | |
var width = window.innerWidth * devicePixelRatio; | |
if (width > 640) { | |
return "high"; | |
} else if (width > 320) { | |
return "medium"; | |
} else { | |
return "small"; // default version | |
} | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://www.smashingmagazine.com/2013/09/16/responsive-images-performance-problem-case-study/
For a more in-depth article about the exact code above.