pauloabmiranda
1/19/2015 - 11:59 AM

Padding Bottom Hack and lazy loading of image relative to the size of the sreen

Padding Bottom Hack and lazy loading of image relative to the size of the sreen

.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%;*/
}
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]);
    }
<div class="lazy-load">
    <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>
</div>
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
            }
};