I am trying to optimize the size of my site when it is being outputted to the client. I am down to 1.9MB and 29KB when caching. The issue is that the first load contains an
On Ubuntu / Chrome 71, Milche's answer does not work consistently for me and the higher resolution image (via img src
) often loads and resolves before the lower resolution image (via css background
) even begins downloading.
My solution is to start with the lower res image as the src
and use the Image class to create an unattached
instance with the high res image. Once it loads, then update the existing
source with the high res image source.
HTML:
JavaScript:
window.addEventListener('load', function() {
loadHighResImage(document.getElementById('my-image'), 'high-res.png')
})
function loadHighResImage(elem, highResUrl) {
let image = new Image()
image.addEventListener('load', () => elem.src = highResUrl)
image.src = highResUrl
}
Fiddle: https://jsfiddle.net/25aqmd67/
This approach works for lower res images that are simply scaled down as well.