Is there any way to set image quality to increase the loading speed?

5

Is there any way I can leave a given image, through CSS, with a lower quality, to increase page load speed?

Example: First load a certain image with the lowest quality, then increase its quality when the user moves the mouse?

    
asked by anonymous 19.10.2015 / 15:37

2 answers

3

Here is a method that works:

CSS

#div_whatever {
   position: whatever;
   background-repeat: no-repeat;
   background-position: whatever whatever; 
   background-image: url(dir/image.jpg);
   /* image.jpg is a low-resolution at 30% quality. */
}

#img_highQuality {
   display: none;
}

HTML

<img id="img_highQuality" src="dir/image.png">
<!-- img.png is a full-resolution image. -->

<div id="div_whatever"></div>

JQuery

$("#img_highQuality").off().on("load", function() {
    $("#div_whatever").css({
        "background-image" : "url(dir/image.png)"
    });
});

What happens

  • A low-resolution background version loads quickly.
  • Meanwhile, the higher-resolution version is loading like a hidden image.
  • When the higher resolution version loads, jQuery swaps the divs with low resolution images for high resolution images.
  • JS VERSION

    This example is for when you need to change many elements.

    CSS:

    .hidden {
       display: none;
    }
    
    #div_whatever {
       position: whatever;
       background-repeat: no-repeat;
       background-position: whatever whatever; 
       background-image: url(dir/image.jpg);
       /* image.jpg is a low-resolution at 30% quality. */
    }
    

    HTML:

    <div id="div_whatever"></div>
    <img id="img_whatever" class="hidden" src="dir/image.png" onload="upgradeImage(this);">
    

    JAVASCRIPT:

    function upgradeImage(object) {
        var id = object.id;
        var target = "div_" + id.substring(4);
    
        document.getElementById(target).style.backgroundImage = "url(" + object.src + ")";
    }
    

    Font Here

        
    19.10.2015 / 15:54
    0

    Use the hover property of css, example:

    .imagem {
      background: url(imagem-com-baixa-qualidade.jpg);
      }
    
    .imagem:hover {
      background: url(imagem-com-alta-qualidade.jpg);
      }
        
    22.10.2015 / 15:27