通过推迟图像来加快页面加载速度 [英] Speed up page load by deferring images

查看:100
本文介绍了通过推迟图像来加快页面加载速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个页面,其中将包含很多大尺寸的图像,因此自然而然地我想确保页面加载不会有太多麻烦.我在 http://24ways.org/2010/中阅读了本文加快内容延迟的网站

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

延迟的方法如下(从页面中拉出,不要在意URL)

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>

然后,一小段js负责图像加载

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

$(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?

谢谢

推荐答案

有点晚了,但是如果它对其他人有好处,Patrick Sexton会在该主题上发表一篇很棒的文章 https://varvy.com/pagespeed/defer-images.html

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

基本上,他提出了相同的建议,仅通过使用基于64位编码的微小图像,他就可以将其图像标签直接放置在HTML中,这具有能够单独控制高度,宽度,高度等属性的好处.与在脚本中创建整个图像标签相比,以这种方式维护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>

这篇关于通过推迟图像来加快页面加载速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆