Speed up page load by deferring images

前端 未结 4 1315
暖寄归人
暖寄归人 2020-12-08 04:29

I am creating a page which will contain a lot of large sized images, so naturally I want to make sure the page loads without too much trouble. I read this article here http:

相关标签:
4条回答
  • 2020-12-08 04:51

    Here's a version showcasing .querySelectorAll:

    function swapSrcAttributes(source) {
      return function(element) {
        element.setAttribute('src', element.getAttribute(source));
      }
    }
    
    function forEach(collection, partial) {
      for (var i = 0; i < collection.length; i++) {
         partial(collection[i]);
      }
    }
    
    function initDeferImages() {
      // for images
      var deferImages = document.querySelectorAll('img[data-src]');
    
      // or you could be less specific and remove the `img`
      deferImages = document.querySelectorAll('[data-src]');
    
      forEach(deferImages, swapSrcAttributes('data-src'));
    }
    
    window.onload = function() {
      initDeferImages();
    }
    

    Here is the compatibility table for .querySelector and .querySelectorAll via https://caniuse.com/#feat=queryselector

    0 讨论(0)
  • 2020-12-08 05:00

    Since April 2019, there is a native support for lazy image loading in Chrome.

    Hopefully, it will be supported in more browsers :)

    0 讨论(0)
  • 2020-12-08 05:02

    This seems to be pretty clean way of deferring images. The only potential problem is if images carry important information as "Data attributes are a new feature in HTML5".

    Another option could be to put images to end of body and use CSS to position them. Personally I would stick to javascript.

    0 讨论(0)
  • 2020-12-08 05:04

    A little late, but in case it benefits others, there is a great article on this topic by Patrick Sexton https://varvy.com/pagespeed/defer-images.html

    He basically is suggesting the same thing, only by using tiny base 64 encoded images, he can place his image tags directly in the HTML which has the benefit of being able to control attributes like height, width, alt, etc individually. It will be a lot easier to maintain your HTML this way as opposed to creating the entire image tag in a script.

    <img src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-src="image1.jpg" alt="image 1">
    <img src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-src="image2.jpg" alt="image 2">
    

    Then your script is simple and generic for all images

    <script>
    function init() {
      var imgDefer = document.getElementsByTagName('img');
      for (var i = 0; i < imgDefer.length; i++) {
        if (imgDefer[i].getAttribute('data-src')) {
          imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src'));
        }
      }
    }
    
    window.onload = init;
    </script>
    
    0 讨论(0)
提交回复
热议问题