by Riccardo Canella

里卡多·卡内拉(Riccardo Canella)

HTML5和Intersection Observer的响应式图像优化简介 (An intro to responsive image optimization with HTML5 and Intersection Observer)

Images often account for most of the downloaded bytes on a web page and often occupy a significant amount of visual space. As a result, optimizing images can frequently yield some of the largest byte savings and performance improvements for your website. The fewer bytes the browser has to download, the less time the user will have to wait for the render of useful content on the screen.

图像通常占据网页上大多数已下载的字节,并且经常占用大量的可视空间。 因此,优化图像通常可以为您的网站节省一些最大的字节并提高性能。 浏览器必须下载的字节越少,用户等待屏幕上有用内容的呈现时间就越少。

Image optimization is both a science and an art. It is a science because there are many well developed techniques and algorithms that can significantly reduce the size of an image. It is an art because there is no one definitive answer.

图像优化既是一门科学,也是一门艺术。 这是一门科学,因为有许多成熟的技术和算法可以显着减小图像的大小。 这是一门艺术,因为没有一个明确的答案。

But how we can optimize our images from mobile form in addition to using image magic or any other web optimization tool?

但是,除了使用图像魔术或任何其他网络优化工具之外,我们如何才能从移动表单优化图像?

img元素 (The img element)

The HTML5 <img> element has been designed to give the developer the ability to optimize the images according to the screen resolution. This is done through two attributes, srcset and sizes. With a very simple syntax, you can instruct the browser to decide which one of the different image sizes are needed:

HTML5 <img>元素旨在使开发人员能够根据屏幕分辨率优化图像。 这是通过两个属性,做srcsetsizes 。 使用非常简单的语法,您可以指示浏览器确定需要哪种不同的图像尺寸:

<img srcset="the-death-star-320w.jpg,the-death-star-480w.jpg 1.5x,the-death-star-640w.jpg 2x"src="the-death-star-640w.jpg"
alt="The Death Star">

The browser, in this case, will choose the image best suited to its resolution. But, the assumption is that the image should be displayed in full screen (100vw). That’s usually not an awful assumption to make.

在这种情况下,浏览器将选择最适合其分辨率的图像。 但是,假定图像应该以全屏(100vw)显示。 通常这并不是一个可怕的假设。

The sizes attribute is used to avoid this problem and, therefore, to help the browser choose the most optimized image for that case. You can use sizes to match your CSS layout exactly and tell the browser exactly how big that image is going to be on every screen size, matching how your breakpoints work in your design.

sizes属性用于避免此问题,因此可以帮助浏览器针对这种情况选择最优化的图像。 您可以使用尺寸来完全匹配CSS布局,并告诉浏览器该图像在每个屏幕尺寸上将要显示多大,以匹配您的断点在设计中的工作方式。

That can get a little complicated, and honestly it might be a little dangerous. You’re putting CSS stuff in markup and you know how that goes. It can be automated or injected server-side. Even in this case the syntax is really very simple:

这可能会有点复杂,说实话,这可能有点危险。 您正在将CSS内容放入标记中,并且您知道如何进行。 它可以是自动化的,也可以在服务器端注入。 即使在这种情况下,语法实际上也非常简单:

<img srcset="the-death-star-320w.jpg,the-death-star-480w.jpg 1.5x,the-death-star-640w.jpg 2x"src="the-death-star-640w.jpg"
sizes="(min-width: 800px) 50vw, 100vw"
alt="The Death Star">

图片元素 (The picture element)

There are different formats for optimizing images for the web, such as webpand jpg2000. But not all browsers are able to support them — Internet Explorer, for example. This should not preclude us from using the most optimized format for most modern browsers.

有多种用于优化网络图像的格式,例如webpjpg2000 。 但是,并非所有浏览器都能够支持它们-例如Internet Explorer。 这不应妨碍我们为大多数现代浏览器使用最优化的格式。

The picture element is a great way to provide alternative sources for image files, so the browser can choose depending on device capabilities. The syntax is very similar to the <video> element and allows you to use the attributes that I first showed you for the <img> element.

图片元素是为图像文件提供替代来源的好方法,因此浏览器可以根据设备功能进行选择。 语法与<video>元素非常相似,并且允许您使用我最初为<img>元素显示的属性。

<picture><source type="image/webp" srcset="the-death-star.webp"><source media=”(min-width: 320px)” srcset=”the-death-star-mn.jpg”><source media=”(min-width: 465px)” srcset=”the-death-star-sm.jpg”><source media=”(min-width: 650px)” srcset=”the-death-star-md.jpg, the-death-star-lg.jpg 1.5x”sizes="(min-width: 800px) 50vw, 100vw"><img src=”the-death-star.jpg” alt=”Flowers” style=”width:auto;”>
</picture>

But can I use the <picture> element everywhere?

但是我可以在任何地方使用<picture>元素吗?

Unfortunately, no. Browsers like Internet Explorer 11 do not support this element.

抱歉不行。 诸如Internet Explorer 11之类的浏览器不支持此元素。

But there is a solution. A very small JS library allows you to use this element, even on unsupported browsers.

但是有一个解决方案 。 很小的JS库允许您即使在不受支持的浏览器上也可以使用此元素。

延迟加载图像 (Lazy loading the images)

One of the most widespread and useful bits of advice I’ve come across is to avoid having the browser download all the images when loading the page. Only download the essential images, and make a lazy loading of the other resources. There are a lot of techniques for lazy loading. These depend on how the page is scrolled, or the next section that the user could visit.

我遇到的最广泛和最有用的建议之一是,避免让浏览器在加载页面时下载所有图像。 仅下载基本映像,并延迟加载其他资源。 延迟加载有很多技术。 这些取决于页面的滚动方式或用户可以访问的下一部分。

If you’ve written lazy loading code before, you may have accomplished your task by using event handlers such as scroll or resize. This approach is the most compatible across browsers. However, modern browsers offer a more performant and efficient way to do the work of checking element visibility. This is performed via the Intersection Observer API.

如果您之前编写过延迟加载代码,则可能已通过使用事件处理程序(例如scrollresize完成了任务。 这种方法是跨浏览器最兼容的。 但是,现代浏览器提供了一种更高效,更有效的方式来完成检查元素可见性的工作。 这是通过Intersection Observer API执行的。

Intersection Observer is easier to use and read than code relying on various event handlers. Developers only need to register an observer to watch elements, rather than writing tedious element visibility detection code. All that’s left to do for the developer is to decide what to do when an element is visible.

与依赖各种事件处理程序的代码相比,Intersection Observer更易于使用和阅读。 开发人员只需注册观察者即可观看元素,而无需编写繁琐的元素可见性检测代码。 开发人员要做的就是决定当元素可见时该怎么做。

<img class="lazy" src="placeholder-image.jpg" data-src="data:image-to-lazy-load-1x.jpg" data-srcset="image-to-lazy-load-2x.jpg 2x, image-to-lazy-load-1x.jpg 1x" alt="I'm an image!"
>

The three relevant pieces of this markup are: the class attribute, and the data-src and data-srcset attributes. The last two are placeholder attributes containing the URL for the image we'll load, once the element is in the viewport.

此标记的三个相关部分是: class属性以及data-srcdata-srcset属性。 最后两个是占位符属性,当元素位于视口中时,占位符属性包含我们将加载的图像的URL。

document.addEventListener("DOMContentLoaded", () => {var lazyImages =[].slice.call(document.querySelectorAll("img.lazy"))if ("IntersectionObserver" in window) {let lazyImageObserver = new IntersectionObserver((entries, observer) => {entries.forEach(function(entry) {if (entry.isIntersecting) {let lazyImage = entry.target;lazyImage.src = lazyImage.dataset.src;lazyImage.srcset = lazyImage.dataset.srcset;lazyImage.classList.remove("lazy");lazyImageObserver.unobserve(lazyImage);}});});lazyImages.forEach(function(lazyImage) {lazyImageObserver.observe(lazyImage);});} else {// Possibly fall back to a more compatible method here}
});

The code is very simple and easy to debug (this is a codepen to see this code in action), but there is a big problem. The Intersection Observer API is not well supported.

该代码非常简单且易于调试( 这是一个可查看该代码实际运行情况的Codepen ),但是存在一个大问题。 Intersection Observer API不受很好的支持。

You will need to either use a polyfill, or implement a lazy loading based on the resize and scroll events.

您将需要使用polyfill ,或者根据resizescroll事件实现延迟加载。

渐进式图像加载 (Progressive image loading)

This is a little tip: when you export your images (JPEG, GIF , PNG) you can check the progressive option (for example on Photoshop or Sketch). Images already render progressively in a web browser. But a progressive image starts off low-resolution, and progressively enhances itself over time.

这是一个小提示:导出图像(JPEG,GIF和PNG)时,可以检查渐进选项(例如在Photoshop或Sketch上)。 图像已经在Web浏览器中逐步呈现。 但是渐进式图像从低分辨率开始,随着时间的推移逐渐增强。

This technique is now used by almost everyone, because it allows you to immediately show a preview of the image to the user and then slowly upload the various details (for example Instagram). This method allows you to prevent users with a slow connection from leaving your site because it displays a white screen.

现在,几乎每个人都使用此技术,因为它使您可以立即向用户显示图像预览,然后慢慢上传各种详细信息(例如Instagram)。 此方法使您可以防止连接速度慢的用户离开您的站点,因为它显示白屏。

最终药 (Final Pill)

Turning to the web, I came across a wonderful article by José M. Pérez on how Medium optimizes and implements progressive image loading.

转向网络,我碰到一个前来精彩的文章由何塞·M.·佩雷斯对中如何优化并实现逐行扫描的图像加载。

If you liked the article please clap and follow me :) Thx and stay tuned ?Follow my last news and tips on Facebook

如果您喜欢这篇文章,请鼓掌并关注我:)谢谢并继续关注?在Facebook上关注我的最新新闻和提示

翻译自: https://www.freecodecamp.org/news/an-intro-to-responsive-image-optimization-with-html5-and-intersection-observer-2a4fbe1473c1/

HTML5和Intersection Observer的响应式图像优化简介相关推荐

  1. 响应式图像_如何为响应图像使用HTML5“图片”,“ srcset”和“大小”

    响应式图像 <picture>是HTML5元素,旨在为我们提供更多的功能和性能更好的响应图像功能. Picture标签不会加载单个图像并尝试调整其大小以适合所有可能的视口尺寸和布局,而是加 ...

  2. html中图片响应式怎么写,如何使用 HTML5 的picture元素处理响应式图片

    图片在响应式网页设计中是出了名的最具挑战性的方面之一.今天我们就来看看如何使用元素来处理响应式图片. 让我们先了解一下问题 固定宽度,像素完美的网站设计已经离我们远去了.在宽屏显示器,互联网电视,多尺 ...

  3. 响应式 ui 模板_带有即用型模板的响应式图像指南

    响应式 ui 模板 by Maciej Nowakowski 通过Maciej Nowakowski 带有即用型模板的响应式图像指南 (A Guide to Responsive Images wit ...

  4. HTML5实践 -- 三步实现响应式设计

    HTML5实践 -- 三步实现响应式设计 响应式web设计现在已经不是一个难事了,如果你还不熟悉他,可以参看我的文章<HTML5实践 -- 流式响应式设计>.如果你是一个初学者,可能响应式 ...

  5. Boostrap 响应式图像

    具体格式如下 <img src="..." class="img-responsive" alt="响应式图像"> 通过将类名设 ...

  6. 响应式图像对齐中心引导3

    本文翻译自:Responsive image align center bootstrap 3 I do a catalog using Bootstrap 3. When displayed on ...

  7. css怎么实现加载的圆圈_图像高清方案——响应式图像让图像加载又快又省

    # 什么是响应式图像 响应式图像指的是根据设备分辨率.设备像素比,甚至是屏幕方向.屏幕尺寸.页面布局等来加载正确图像,并且图片体积尽可能的小,视觉效果足够高清. 一个真实的场景:用户上传了一张高清图片 ...

  8. 响应式图像--图片自适应大小

    Foreword 做项目的过程中遇到了一个图片拉伸的问题,做的是手机端的页面,当让其以电脑端页面显示的时候,图片被拉伸的有那么点丑!所以改改它! Why 为什么会出现这样的情况呢? 1.因为图片是放在 ...

  9. 前端src显示服务器图片,响应式图像之srcset和sizes属性

    再一次提到响应式图像,司空见惯了,有点腻了,如果你看完下面的内容,我觉得你会对响应式图像处理会有新的认知.这篇文章我也是无意在进步博客上看到的,认真的看了几遍,有些东西讲的很不错,所以想分享下. 开发 ...

最新文章

  1. 主要操作系统体系结构
  2. Python--练习及面试题
  3. ERP选型 SAP PK Oracle
  4. Openg-三角形绘制
  5. 32位CPU和64位CPU 区别
  6. 表单新增元素与属性(control、placehoulder、list、AutoComplete、pattern、SelectionDirection、indeterminate属性)
  7. 合肥特殊教育中专学校计算机,安徽省特殊教育中专学校
  8. 耿美玉起诉饶毅名誉侵权,法院判了!驳回请求,但对饶毅方也应给予批评
  9. mysql info commit_mysql show processlist 发现大量的commit
  10. 6.FreeRTOS学习笔记-信号量
  11. python rsa库_Python中rsa模块【sign 加签验签】的使用
  12. 在centos7中安装nodejs(npm )
  13. 【jQuery 遍历】 - map() 方法
  14. 11.无限分类表的数据库设计
  15. Git hub加载慢?下载慢?浏览慢?几个小技巧让你一键起飞!
  16. vue 数字上下滚动抽奖
  17. 卡方检验四格表怎么做_运用SPSS进行医学诊断数据的Kappa一致性检验 ——【杏花开医学统计】...
  18. win32 WaitCommEvent
  19. 分组交换比起电路交换快速的原因
  20. Python--几种set集合去重的方法

热门文章

  1. 第一条Pulsar消息发送
  2. 【Linux】线程同步之信号量同步
  3. 草稿 断开式数据连接
  4. 解决 吃货阶段02 0928
  5. 爬虫-04-常见的请求头
  6. nginx之反向代理服务器
  7. CentOS6.9安装Kafka
  8. 数据库中字段随机添加汉字
  9. zabbix监控vsftp服务,发生故障并自动恢复
  10. flask笔记3-模板