响应式图像

    技术2022-07-11  135

    响应式图像

    It doesn't take being a performance fanatic to know that images can really slow down a page's load time.  We've come a long way when it comes to images, from lazy loading them to using better image formats like WebP, but they all involve loading the same static image URL which may be good for desktops but not for mobile devices, and visa versa.  We do have srcset with img tags now, but that can be difficult to maintain for dynamic, user-driven websites.

    知道图像确实会减慢页面的加载时间并不需要对性能感到狂热。 从图像的延迟加载到使用更好的图像格式(如WebP) ,我们在图像处理方面已经走了很长一段路,但它们都涉及到加载相同的静态图像URL,这可能对台式机有利,但对移动设备不利,反之亦然。 现在,我们确实具有带有img标签的srcset ,但是对于动态的,用户驱动的网站而言,这可能很难维护。

    My experiments with Cloudinary have shown me than they have a solution for almost everything when it comes to media.  My prior experiments include:

    我对Cloudinary进行的实验向我展示了他们几乎可以解决媒体方面的所有问题。 我之前的实验包括:

    Image Optimization with Cloudinary

    使用Cloudinary进行图像优化

    Generate Waveform Images from Audio with Cloudinary

    使用Cloudinary从音频生成波形图像

    How to Deliver a Smooth Playback without Interruptions (Buffering)

    如何在不中断的情况下提供流畅的播放(缓冲)

    Remove Photo Backgrounds with Cloudinary

    使用Cloudinary删除照片背景

    HTML5 Video Player Best Practices

    HTML5视频播放器最佳做法

    Another new way of optimizing image delivery is called "client hints":  a new set of HTTP request headers sent to the server to provide information about the device, allowing more intelligent output.  Here's the precise explanation of client hints from the standards document:

    优化图像传送的另一种新方法称为“ 客户端提示 ”:发送到服务器的一组新的HTTP请求标头,以提供有关设备的信息,从而实现更智能的输出。 这是标准文档中对客户提示的精确解释:

    This specification defines a set of HTTP request header fields, colloquially known as Client Hints, to address this. They are intended to be used as input to proactive content negotiation; just as the Accept header field allows clients to indicate what formats they prefer, Client Hints allow clients to indicate a list of device and agent specific preferences.

    该规范定义了一组HTTP请求标头字段(通常称为客户端提示)来解决此问题。 它们旨在用作主动内容协商的输入; 就像“接受标头”字段允许客户端指示他们喜欢的格式一样,“客户端提示”允许客户端指示设备和代理特定的首选项列表。

    Let's have a look at current "responsive image" hints and then image optimization with client hints!

    让我们看一下当前的“响应图像”提示,然后使用客户端提示进行图像优化!

    使用CSS的响应式图像 (Responsive Images with CSS)

    There are currently two ways I use CSS for responsive images.  The first is by setting a max-width on images:

    目前,我有两种方法将CSS用于响应图像。 第一种是通过在图像上设置max-width :

    img { max-width: 100%; }

    The second method is by scoping background images with CSS media queries:

    第二种方法是使用CSS媒体查询确定背景图像的范围:

    .logo { background-image: url('/path/to/tiny-logo.png'); } @media (min-width: 1024px) { .logo { background-image: url('/path/to/large-logo.png'); } }

    Both work each as their own issues: the first method always serves the large image file size regardless of screen size, the second method bloats your CSS (image scoping every image -- gross!) and requires the use of a background image.

    两者都有各自的问题:第一种方法始终提供较大的图像文件大小,而不管屏幕大小如何;第二种方法使CSS膨胀(图像范围限制每个图像-总体!),并且需要使用背景图像。

    使用JavaScript的响应式图像 (Responsive Images with JavaScript)

    There are loads of libraries for responsive images:

    有很多用于响应图像的库:

    Truly Responsive Images with responsive-images.js

    使用响应图像.js实现真正的响应图像

    picturefill

    图片填充

    lazySizes

    lazySizes

    There are many more libraries out there that will do the job, but my problem with these JavaScript-based approaches is that they can sometimes add huge weight to the page and they don't provide a "native" image approach, i.e. you have to wait for the DOM to load, then analyze the images, then set widths and make requests, etc.  A more classic approach would be more performant.

    还有更多的库可以完成这项工作,但是这些基于JavaScript的方法的问题是它们有时可能会增加页面的权重,并且它们不提供“本机”图像方法,也就是说,您必须等待DOM加载,然后分析图像,然后设置宽度和发出请求等。更经典的方法将具有更高的性能。

    <img srcset> (<img srcset> )

    The current method for providing responsive image paths is a bit ugly and can be tedious to create:

    提供响应图像路径的当前方法有点丑陋,创建起来可能很繁琐:

    <img sizes="100vw" srcset="tiny.jpg 320w, small.jpg 512w, medium.jpg 640w, large.jpg 1024w, huge.jpg 1280w, enormous.jpg 2048w" src="fallback.jpg" alt="To each according to his ability" />

    Essentially we specify a new image for specified widths in a sort odd single-string format.  For this method you need to create separate images or engineer a smart querystring-based system for dynamically generating images.  In many cases both options are impractical.

    本质上,我们以排序的单字符串格式为指定的宽度指定了一个新图像。 对于这种方法,您需要创建单独的图像或设计一个基于智能查询字符串的系统来动态生成图像。 在许多情况下,这两种选择都不切实际。

    使用客户端提示 (Using Client Hints)

    The first part of using client hints is providing a single meta tag with the hints you'd like to provide to the server:

    使用客户端提示的第一部分是向单个meta标签提供您想要提供给服务器的提示:

    <meta http-equiv="Accept-CH" content="DPR, Width">

    With the snippet above, we direct the browser to provide width and DPR (device pixel ratio) hints to server during the request to the image.  Using Chrome's "Network" panel we can see those headers being sent:

    通过上面的代码段,我们指导浏览器在对图像的请求期间向服务器提供宽度和DPR(设备像素比率)提示。 使用Chrome的“网络”面板,我们可以看到正在发送的标头:

    If we stop and think for a moment, there's a lot we can do by pulling the Width, DPR, and other hints from their headers:

    如果我们停下来思考片刻,可以通过从标题中拉出Width,DPR和其他提示来做很多事情:

    Store the data so we can analyze patterns and possibly cut different image dimensions

    存储数据,以便我们分析图案并可能切割不同的图像尺寸 Generate, store, and return a custom image for the given file size

    生成,存储并返回给定文件大小的自定义图像 Return a different image type for a given device

    返回给定设备的其他图像类型

    The client hint is something we've always wanted:  a tip from the client as to its size and other visual characteristics!  I love that client hints are easy to implement on the client side: add a <meta> tag, add a sizes attribute to your image, and you're golden. The hard part is the server side: you need to add dynamic, optimized response logic -- that's where Cloudinary can help.

    客户提示是我们一直想要的:客户提示其大小和其他视觉特征! 我喜欢客户端提示很容易在客户端实现:添加<meta>标记,为图像添加sizes属性,然后您就很高兴了。 困难的部分是服务器端:您需要添加动态的,优化的响应逻辑,这是Cloudinary可以提供帮助的地方。

    客户对Cloudinary的提示 (Client Hints with Cloudinary)

    Cloudinary wants to make creating and managing responsive imagery their problem.  Cloudinary offers APIs for many languages (Python, Node.js, etc.), even allowing delivery of dynamic images via a URL.  Let's create an image with an automatic DPR hint:

    Cloudinary希望使创建和管理响应式图像成为他们的问题。 Cloudinary提供了适用于多种语言(Python,Node.js等)的API,甚至允许通过URL交付动态图像。 让我们创建一个带有自动DPR提示的图像:

    <meta http-equiv="Accept-CH" content="DPR"> <img src="http://res.cloudinary.com/demo/w_512,dpr_auto/bike.jpg">

    The w_512,dpr_auto portion of the image URL triggers sending a different image resource to each user based on their context. For browsers that support client hints, 1x devices will receive 1x resources; 2x screens will receive 2x resources; display density triggers a difference in resource delivery.

    图像URL的w_512,dpr_auto部分触发根据每个用户的上下文向每个用户发送不同的图像资源。 对于支持客户端提示的浏览器,1x设备将获得1x资源。 2x屏幕将获得2x资源; 显示密度触发资源交付的差异。

    Now let's do automatic image width with client hints:

    现在让我们使用客户端提示进行自动图像宽度设置:

    <img src="https://res.cloudinary.com/demo/w_auto,dpr_auto/bike.jpg">

    Same effect:  w_auto sends a different image size from the same URL based on the client hint -- incredibly convenient when creating dynamic content -- no need for ugly srcset management!

    相同的效果: w_auto根据客户端提示从同一URL发送不同的图像大小-创建动态内容时非常方便-无需难看的srcset管理!

    Cloudinary的高级客户端提示 (Advanced Client Hints with Cloudinary)

    w_auto can take two optional parameters:

    w_auto 可以采用两个可选参数 :

    <!-- In the <head> --> <meta http-equiv="Accept-CH" content="DPR, Width"> <!-- Image in the page --> <img sizes="100vw" src="http://res.cloudinary.com/demo/w_auto:100:400/bike.jpg" alt="Smiling girl with a bike." />

    Let's break down the code above, specifically the w_auto:100:400 piece:

    让我们分解上面的代码,特别是w_auto:100:400片段:

    100 represents the increment by which the image is calculated with relation to the client hint, unless 1 is provided, in which case the image will then be scaled to the exact layout width (this is bad -- if the client isn't a standard device width, performance will be impacted). If the client hint for Width is 444, the image will round up and a 500 pixel image will be returned.

    100代表相对于客户端提示的图像计算增量,除非提供1 ,否则图像将被缩放到确切的布局宽度(这很不好-如果客户端不是标准的设备宽度,性能会受到影响)。 如果客户端对Width提示是444 ,则图像将四舍五入,并返回500像素的图像。

    400 represents the fallback image width in the case that the client hints API isn't supported by the browser or a hint simply isn't sent (i.e. Width isn't listed in the <meta> tag). If this argument isn't provided, the full image size is returned, so if your image is very large (i.e. an original photo), you'll definitely want to provide this argument.

    400表示在浏览器不支持客户端提示API或根本不发送提示(即, Width未在<meta>标记中列出)的情况​​下的备用图片宽度。 如果未提供此参数,则返回完整的图像大小,因此,如果您的图像很大(例如原始照片),则肯定要提供此参数。

    Unfortunately only Opera and Chrome support client hints at this time, while Firefox and Edge are considering adding client hint support.  I will say I find this new advancement a perfect marriage of server and client side communication when it comes to assets and device display.  Let's hope client hints are globally adopted -- we'll be able to really tighten up image delivery, especially when you use an awesome service like Cloudinary!

    不幸的是,目前只有Opera和Chrome支持客户端提示,而Firefox和Edge正在考虑添加客户端提示支持。 我会说,在资产和设备显示方面,我发现这项新进展是服务器和客户端通信的完美结合。 让我们希望客户的提示在全球范围内得到采用-我们将能够真正加强图像的交付,尤其是当您使用Cloudinary这样的出色服务时!

    翻译自: https://davidwalsh.name/responsive-images-client-hints

    响应式图像

    Processed: 0.013, SQL: 9