使用媒体查询控制图片下载

Using media queries to control image downloads

如果我创建一个容器并想根据媒体查询设置背景图像,为什么浏览器(Firefox,Chrome)下载中等大小的图像,如果已经下载了大图像?这似乎完全违背了这一点(即节省带宽)。

HTML

<div id="background"></div>

CSS

#background {
    width: 100%;
    height: 400px;
    background-image: url(/content/images/2016/04/airport-small.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
}

@media (min-width: 500px) {
  #background {
    background: url(/content/images/2016/04/airport-medium.jpg);
  }
}
@media (min-width: 800px) {
  #background {
    background: url(/content/images/2016/04/airport-large.jpg);
  }
}

如果我加载页面,浏览器会下载 -large.jpg,在此设置中。如果我调整屏幕大小(低于 800 像素),浏览器会下载并呈现 -medium.jpg,依此类推。

我怎样才能避免这种情况?

您正在调整 window 的大小,这会导致执行多个媒体查询,从而导致下载多个图像。

但是您是一名 Web 开发人员,为了测试需要重新调整浏览器的大小。实际用户通常不会这样做。用户只需登陆您的网站就可以开展业务 – 在一个屏幕尺寸上

在您的情况下,如果该用户使用浏览器宽度为 500px - 799px 的设备,he/she 将获得中 jpg and/or 小 jpg,具体取决于浏览器(见下文) ).

请注意,屏幕宽度大于 800 像素的用户可能会看到所有三张图片。 (匹配 min-width: 800px 的 window 也匹配 min-width: 500px。)

根据对 Media Query & Asset Downloading Results 的评论,浏览器行为在图像下载方面有所不同。特别是,请参阅测试 #4。


此外,考虑 picture 元素,它告诉浏览器哪个图像最适合特定的屏幕尺寸.

4.8.2 The picture element

The picture element is a container which provides multiple sources to its contained img element to allow authors to declaratively control or give hints to the user agent about which image resource to use, based on the screen pixel density, viewport size, image format, and other factors.

<picture>
   <source srcset="airport-small.jpg"  media="(max-width: 499px)">
   <source srcset="airport-medium.jpg" media="(min-width: 500px) and (max-width: 799px)">
   <source srcset="airport-large.jpg"  media="(min-width: 800px)">
   <img src="airport-small.jpg" alt="">
</picture>

如果所有 source 元素的计算结果为假,则应用 img 元素。这是一个有用的后备方案,因为 Internet Explorer 不支持 picture


参考文献:

我认为这里冲突的主要原因是您假设实施媒体查询是为了节省带宽。它们被实现为以不同的尺寸显示不同的东西,仅此而已。你选择以不同尺寸显示相同图像的事实只是你决定如何使用它们,而媒体查询只是忠实地做他们一直承诺做的事情:向用户展示你告诉它要向用户展示的内容.

我建议评估这是否真的值得投入时间和代码(请记住,大多数用户不会调整 window 的大小或旋转移动设备,而那些这样做的人可能不会'被闪现和重新加载推迟)。如果你决定这样做,它不会只通过 CSS。你最好的办法是研究 JavaScript 方法来做到这一点,例如将 class loaded-large 添加到 body 标签 onload,然后为较小的图像编写 CSS 规则当 body 标签没有 class='loaded-large'.

时加载

希望对您有所帮助。