Speed up page load by deferring images

前端 未结 4 1327
暖寄归人
暖寄归人 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

提交回复
热议问题