Load a low-res background image first, then a high-res one

前端 未结 6 901
陌清茗
陌清茗 2020-12-04 17:56

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

6条回答
  •  北海茫月
    2020-12-04 19:01

    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:

    Title
    

    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.

提交回复
热议问题