Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@zanonnicola
Created November 3, 2014 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zanonnicola/9e285cd78d87a34f66c8 to your computer and use it in GitHub Desktop.
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.
<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>
@Cordazar
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment