preload image with javascript and display when ready

前端 未结 2 826
谎友^
谎友^ 2020-12-20 08:45

I want to show a low-res image and start loading the hi-res image after the complete page has rendered. Only when the hi-res image is completely loaded, I want to replace th

相关标签:
2条回答
  • 2020-12-20 09:33

    In your HTML

    <img src='lowres.gif id='mypic'>
    
    <script>
      var img = document.getElementById("mypic");
      var img2 = new Image();
      var img2.onload = function() {
        img.parent.insertBefore(img2, img);
        // Or hide it.
        img.style.display = "none";
      };
      var img2.src = XXXXX;
    </script>
    
    0 讨论(0)
  • 2020-12-20 09:35

    Use this script to preload the images:

    <div class="hidden">
        <script type="text/javascript">
            <!--//--><![CDATA[//><!--
                var images = new Array()
                function preload() {
                    for (i = 0; i < preload.arguments.length; i++) {
                        images[i] = new Image()
                        images[i].src = preload.arguments[i]
                    }
                }
                preload(
                    "images-1.png",
                    "images-2.png",
                    "images-3.png",
                    "images-4.png"
                )
            //--><!]]>
        </script>
    </div>
    

    Then use low-res images in your html as you need and change to hi-res images when needed. The preloaded image is there for you.

    $(window).load(function(){
       $(selector).css('background-image',images[0]);
    });
    
    0 讨论(0)
提交回复
热议问题