Javascript 通过延迟图像加快页面加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12396068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:53:19  来源:igfitidea点击:

Speed up page load by deferring images

javascriptjquerydeferred-loading

提问by Huangism

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://24ways.org/2010/speed-up-your-site-with-delayed-content

我正在创建一个包含大量大尺寸图像的页面,所以我很自然地希望确保页面加载时不会遇到太多麻烦。我在这里阅读了这篇文章http://24ways.org/2010/speed-up-your-site-with-delayed-content

The method of deferring is as follows (pulled from page, don't mind the URL)

延迟的方法如下(从页面拉出来的,不要介意网址)

<div>
    <h4>
        <a href="http://allinthehead.com/" data-gravatar-hash="13734b0cb20708f79e730809c29c3c48">
            Drew McLellan
        </a>
    </h4>
</div>

then later a snippet of js takes care of the image loading

然后稍后一段 js 负责图像加载

$(window).load(function() {
    $('a[data-gravatar-hash]').prepend(function(index){
        var hash = $(this).attr('data-gravatar-hash')
        return '<img width="100" height="100" alt="" src="http://www.gravatar.com/avatar.php?size=100&amp;gravatar_id=' + hash + '">'
    });
});

I don't plan on doing this for every image but definitely for some image which I don't need it to show up at page load time.

我不打算为每个图像都这样做,但绝对是为一些我不需要它在页面加载时显示的图像。

Is this the best way to go or are there better ways to achieve faster page load by deferring images?

这是最好的方法还是有更好的方法通过延迟图像来实现更快的页面加载?

Thanks

谢谢

回答by jsolis

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

有点晚了,但如果它有利于其他人,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.

他基本上是在暗示同样的事情,只需使用微小的 base 64 编码图像,他就可以将他的图像标签直接放在 HTML 中,这样的好处是能够单独控制高度、宽度、alt 等属性。与在脚本中创建整个图像标签相比,以这种方式维护 HTML 会容易得多。

<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>

回答by nrodic

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".

这似乎是延迟图像的非常干净的方式。唯一的潜在问题是图像是否带有重要信息,因为“数据属性是 HTML5 中的一项新功能”。

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

另一种选择是将图像放在正文的末尾并使用 CSS 来定位它们。我个人会坚持使用 javascript。

回答by KIR

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

自 2019 年 4 月起,Chrome 提供了对延迟图像加载本机支持

Hopefully, it will be supported in more browsers :)

希望更多浏览器支持它:)

回答by Sgnl

Here's a version showcasing .querySelectorAll:

这是一个版本展示.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 .querySelectorand .querySelectorAllvia https://caniuse.com/#feat=queryselector

下面是兼容性表.querySelector,并.querySelectorAll通过https://caniuse.com/#feat=queryselector