CSS “display:none”会阻止加载图像吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12158540/
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
Does "display:none" prevent an image from loading?
提问by nasty
Every responsive website development tutorial recommends using the display:none
CSS property to hide content from loading on mobile browsers so the website loads faster. Is it true? Does display:none
not load the images or does it still load the content on mobile browser? Is there any way to prevent loading unnecessary content on mobile browsers?
每个响应式网站开发教程都建议使用display:none
CSS 属性来隐藏移动浏览器上加载的内容,从而使网站加载速度更快。这是真的吗?难道display:none
不加载图像或它仍然加载在手机浏览器的内容?有什么办法可以防止在移动浏览器上加载不必要的内容?
采纳答案by Denys Séguret
Browsers are getting smarter. Today your browser (depending on the version) might skip the image loading if it can determine it's not useful.
浏览器变得越来越智能。今天您的浏览器(取决于版本)可能会跳过图像加载,如果它可以确定它没有用。
The image has a display:none
style but its size may be read by the script.
Chrome v68.0 does not load images if the parent is hidden.
图像具有display:none
样式,但脚本可以读取其大小。如果父隐藏,Chrome v68.0 不会加载图像。
You may check it there : http://jsfiddle.net/tnk3j08s/
您可以在那里查看:http: //jsfiddle.net/tnk3j08s/
You could also have checked it by looking at the "network" tab of your browser's developer tools.
您也可以通过查看浏览器开发人员工具的“网络”选项卡来检查它。
Note that if the browser is on a small CPU computer, not having to render the image (and layout the page) will make the whole rendering operation faster but I doubt this is something that really makes sense today.
请注意,如果浏览器在小型 CPU 计算机上,不必渲染图像(和布局页面)将使整个渲染操作更快,但我怀疑这在今天真的有意义。
If you want to prevent the image from loading you may simply not add the IMG element to your document (or set the IMG src
attribute to "data:"
or "about:blank"
).
如果您想阻止图像加载,您可能只是不将 IMG 元素添加到您的文档中(或将 IMGsrc
属性设置为"data:"
或"about:blank"
)。
回答by Brent
If you make the image a background-image of a div in CSS, when that div is set to "display: none", the image will not load. When CSS is disabled, it still will not load, because, well, CSS is disabled.
如果在 CSS 中将图像设为 div 的背景图像,当该 div 设置为“display: none”时,图像将不会加载。当 CSS 被禁用时,它仍然不会加载,因为 CSS 被禁用。
回答by DMTintner
The answer is not as easy as a simple yes or no. Check out the results of a test I recently did:
答案并不像简单的“是”或“否”那么简单。看看我最近做的一个测试的结果:
- In Chrome: All 8 screenshot-* images loaded (img 1)
- In Firefox: Only the 1 screenshot-* image loaded that is currently being displayed (img 2)
- 在 Chrome 中:加载了所有 8 个屏幕截图-* 图像(img 1)
- 在 Firefox 中:仅加载了当前正在显示的 1 个屏幕截图-* 图像 (img 2)
So after digging further I found this, which explains how each browser handles loading img assets based on css display: none;
所以在进一步挖掘之后,我发现了这个,它解释了每个浏览器如何根据 css display: none; 处理加载 img 资产。
Excerpt from the blog post:
博文摘录:
- Chrome and Safari (WebKit):
WebKit downloads the file every time except when a background is applied through a non-matching media-query.- Firefox:
Firefox won't download the image called with background image if the styles are hidden but they will still download assets from img tags.- Opera:
Like Firefox does, Opera won't load useless background-images.- Internet Explorer:
IE, like WebKit will download background-images even if they have display: none; Something odd appears with IE6 : Elements with a background-image and display: none set inline won't be downloaded... But they will be if those styles aren't applied inline.
- Chrome 和 Safari (WebKit):
WebKit 每次都会下载文件,除非通过不匹配的媒体查询应用背景。- Firefox:
如果样式被隐藏,Firefox 将不会下载使用背景图片调用的图片,但它们仍会从 img 标签下载资源。- Opera:
像 Firefox 一样,Opera 不会加载无用的背景图像。- Internet Explorer:
IE 和 WebKit 一样会下载背景图片,即使它们有 display: none;IE6 出现了一些奇怪的事情:带有背景图像和显示的元素:不会下载内联设置的无...但是如果这些样式没有内联应用,它们将会下载。
回答by Evgenia Manolova
HTML5 <picture>
tag will help you to resolve the right image source depending on the screen width
HTML5<picture>
标签将帮助您根据屏幕宽度解析正确的图像源
Apparently the browsers behaviour hasn't changed much over the past 5 years and many would still download the hidden images, even if there was a display: none
property set on them.
显然,浏览器的行为在过去 5 年里没有太大变化,许多人仍然会下载隐藏的图像,即使display: none
它们设置了属性。
Even though there's a media queriesworkaround, it could only be useful when the image was set as a background in the CSS.
即使有媒体查询解决方法,它也只有在将图像设置为 CSS 中的背景时才有用。
While I was thinking that there's just a JS solution to the problem (lazy load, picturefill, etc.), it appeared that there's a nice pure HTML solution that comes out of the box with HTML5.
虽然我认为这个问题只有一个 JS 解决方案(延迟加载、图片填充等),但似乎有一个很好的纯 HTML 解决方案,它是 HTML5 开箱即用的。
And that is the <picture>
tag.
这就是<picture>
标签。
Here's how MDNdescribes it:
以下是MDN 的描述:
The HTML
<picture>
elementis a container used to specify multiple<source>
elements for a specific<img>
contained in it. The browser will choose the most suitable source according to the current layout of the page (the constraints of the box the image will appear in) and the device it will be displayed on (e.g. a normal or hiDPI device.)
的HTML
<picture>
元素是用于指定多个容器<source>
为特定的元素<img>
载于它。浏览器将根据页面的当前布局(图像将出现在其中的框的约束)和将在其上显示的设备(例如普通或 hiDPI 设备)选择最合适的来源。
And here's how to use it:
以下是如何使用它:
<picture>
<source srcset="mdn-logo-wide.png" media="(min-width: 600px)">
<img src="mdn-logo-narrow.png" alt="MDN">
</picture>
The logic behind
背后的逻辑
The browser would load the source of the img
tag, only if none of the media rules applies. When the <picture>
element is not supported by the browser, it will again fallback to showing the img
tag.
img
仅当没有任何媒体规则适用时,浏览器才会加载标签的来源。当<picture>
浏览器不支持该元素时,它将再次回退到显示img
标签。
Normally you'd put the smallest image as the source of the <img>
and thus not load the heavy images for larger screens. Vice versa, if a media rule applies, the source of the <img>
will not be downloaded, instead it will download the url's contents of the corresponding <source>
tag.
通常,您会将最小的图像作为来源,<img>
因此不会为较大的屏幕加载较重的图像。反之亦然,如果媒体规则适用,<img>
则不会下载的来源,而是会下载相应<source>
标签的 url 内容。
Only pitfall here is that if the element is not supported by the browser, it will only load the small image. On the other hand in 2017 we ought to think and code in the mobile firstapproach.
这里唯一的缺陷是如果浏览器不支持该元素,它只会加载小图像。另一方面,在 2017 年,我们应该以移动优先的方式思考和编码。
And before someone got too exited, here's the currentbrowser support for <picture>
:
在有人退出之前,这是当前的浏览器支持<picture>
:
Desktop browsers
桌面浏览器
Mobile browsers
移动浏览器
More about the browser support you can find on Can I use.
有关浏览器支持的更多信息,您可以在Can I use上找到。
The good thing is that html5please's sentence is to use it with a fallback. And I personally intend to take their advise.
好消息是html5please的句子是将其与后备一起使用。我个人打算接受他们的建议。
More about the tag you can find in the W3C's specification. There's a disclaimer there, which I find important to mention:
您可以在W3C 的规范 中找到有关该标签的更多信息。那里有一个免责声明,我觉得很重要:
The
picture
element is somewhat different from the similar-lookingvideo
andaudio
elements. While all of them containsource
elements, the source element'ssrc
attribute has no meaning when the element is nested within apicture
element, and the resource selection algorithm is different. As well, thepicture
element itself does not display anything; it merely provides a context for its containedimg
element that enables it to choose from multiple URLs.
该
picture
元素与外观相似的video
和audio
元素有些不同。虽然它们都包含source
元素,但是src
当元素嵌套在一个picture
元素中时,源元素的属性没有意义,资源选择算法也不同。同样,picture
元素本身不显示任何内容;它只是为其包含的img
元素提供一个上下文,使其能够从多个 URL 中进行选择。
So what it says is that it only helps you improve the performance when loading an image, by providing some context to it.
所以它说的是,它只能通过提供一些上下文来帮助您提高加载图像时的性能。
And you can still use some CSS magic in order to hide the image on small devices:
您仍然可以使用一些 CSS 魔法来隐藏小型设备上的图像:
<style>
picture { display: none; }
@media (min-width: 600px) {
picture {
display: block;
}
}
</style>
<picture>
<source srcset="the-real-image-source" media="(min-width: 600px)">
<img src="a-1x1-pixel-image-that-will-be-hidden-in-the-css" alt="MDN">
</picture>
Thus the browser will not displaythe actual image and will only download the 1x1
pixel image (which can be cached if you use it more than once). Be aware, though, that if the <picture>
tag is not supported by the browser, even on descktop screens the actual image won'tbe displayed (so you'll definitely need a polyfill backup there).
因此浏览器不会显示实际图像,只会下载1x1
像素图像(如果您多次使用它可以缓存)。但是请注意,如果<picture>
浏览器不支持该标签,即使在桌面屏幕上也不会显示实际图像(因此您肯定需要在那里进行 polyfill 备份)。
回答by Dorian
Yes it will render faster, slightly, only because it doesn't have to render the image and is one less element to sort on the screen.
是的,它会稍微渲染得更快,只是因为它不必渲染图像并且在屏幕上要排序的元素少了一个。
If you don't want it loaded, leave a DIV empty where you can load html into it later containing an <img>
tag.
如果您不想加载它,请将 DIV 留空,您可以稍后将包含<img>
标签的html 加载到其中。
Try using firebug or wireshark as I've mentioned before and you'll see that the files DO get transferred even if display:none
is present.
尝试使用我之前提到的 firebug 或 wireshark,您会看到即使display:none
存在文件也会被传输。
Opera is the only browser which will not load the image if the display is set to none.Opera has now moved to webkit and will render all images even if their display is set to none.
如果显示设置为无,Opera 是唯一不会加载图像的浏览器。Opera 现在已经转移到 webkit 并且会渲染所有图像,即使它们的显示设置为无。
Here is a testing page that will prove it:
这是一个可以证明这一点的测试页面:
回答by Juanma Menendez
** 2019 Answer**
** 2019 答案**
In a normal situation display:none
doesn't prevent the image to be downloaded
在正常情况下display:none
不会阻止下载图像
/*will be downloaded*/
#element1 {
display: none;
background-image: url('https://picsum.photos/id/237/100');
}
But if an ancestor element has display:none
then the descendant's images will not be downloaded
但是如果祖先元素有,display:none
那么后代的图像将不会被下载
/* Markup */
<div id="father">
<div id="son"></div>
</div>
/* Styles */
#father {
display: none;
}
/* #son will not be downloaded because the #father div has display:none; */
#son {
background-image: url('https://picsum.photos/id/234/500');
}
Other situations that prevent the image to be downloaded:
其他阻止图片下载的情况:
1- The target element doesn't exist
1-目标元素不存在
/* never will be downloaded because the target element doesn't exist */
#element-dont-exist {
background-image: url('https://picsum.photos/id/240/400');
}
2- Two equal classes loading different images
2- 两个相等的类加载不同的图像
/* The first image of #element2 will never be downloaded because the other #element2 class */
#element2 {
background-image: url('https://picsum.photos/id/238/200');
}
/* The second image of #element2 will be downloaded */
#element2 {
background-image: url('https://picsum.photos/id/239/300');
}
You can watch for yourself here: https://codepen.io/juanmamenendez15/pen/dLQPmX
回答by ninja_corp
The background-image of a div element will loadif the div is set do 'display:none'.
如果将 div 设置为“显示:无”,则会加载div 元素的背景图像。
Anyway, if that same div has a parent and that parent is set to 'display:none', the background-image of the child element will not load. :)
无论如何,如果同一个 div 有一个父元素并且该父元素设置为“display:none”,则子元素的背景图像将不会加载。:)
Example using bootstrap:
使用引导程序的示例:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="col-xs-12 visible-lg">
<div style="background-image: url('http://via.placeholder.com/300x300'); background-repeat:no-repeat; height: 300px;">lg</div>
</div>
<div class="col-xs-12 visible-md">
<div style="background-image: url('http://via.placeholder.com/200x200'); background-repeat:no-repeat; height: 200px;">md</div>
</div>
<div class="col-xs-12 visible-sm">
<div style="background-image: url('http://via.placeholder.com/100x100'); background-repeat:no-repeat; height: 100px">sm</div>
</div>
<div class="col-xs-12 visible-xs">
<div style="background-image: url('http://via.placeholder.com/50x50'); background-repeat:no-repeat; height: 50px">xs</div>
</div>
回答by onlyurei
Quirks Mode: images and display: none
When image has
display: none
or is inside an element withdisplay:none
, the browser may opt not to download the image until thedisplay
is set to another value.Only Opera downloads the image when you switch the
display
toblock
. All other browsers download it immediately.
当图像具有
display: none
或位于带有 的元素内时display:none
,浏览器可能会选择不下载图像,直到将display
设置为另一个值。当您切换
display
到block
. 所有其他浏览器都会立即下载它。
回答by commonpike
If so is there a way to not load the unnecessary content on mobile browsers?
如果是这样,有没有办法不在移动浏览器上加载不必要的内容?
use <img src="" srcset="">
用 <img src="" srcset="">
http://www.webdesignerdepot.com/2015/08/the-state-of-responsive-images/
http://www.webdesignerdepot.com/2015/08/the-state-of-responsive-images/
回答by ats
如果在 CSS 中将图像设为 div 的背景图像,当该 div 设置为“显示:无”时,图像将不会加载。
Just expanding on Brent's solution.
只是扩展布伦特的解决方案。
You can do the following for a pure CSS solution, it also makes the img box actually behave like an img box in a responsive design setting (that's what the transparent png is for), which is especially useful if your design uses responsive-dynamically-resizing images.
您可以为纯 CSS 解决方案执行以下操作,它还使 img 框实际上表现得像响应式设计设置中的 img 框(这就是透明 png 的用途),如果您的设计使用响应式动态,这尤其有用-调整图像大小。
<img style="display: none; height: auto; width:100%; background-image:
url('img/1078x501_1.jpg'); background-size: cover;" class="center-block
visible-lg-block" src="img/400x186_trans.png" alt="pic 1 mofo">
The image will only be loaded when the media query tied to visible-lg-block is triggered and display:none is changed to display:block. The transparent png is used to allow the browser to set appropriate height:width ratios for your <img> block (and thus the background-image) in a fluid design (height: auto; width: 100%).
仅当与visible-lg-block 绑定的媒体查询被触发并且display:none 更改为display:block 时才会加载图像。透明 png 用于允许浏览器在流体设计(高度:自动;宽度:100%)中为 <img> 块(以及背景图像)设置适当的高度:宽度比率。
1078/501 = ~2.15 (large screen)
400/186 = ~2.15 (small screen)
So you end up with something like the following, for 3 different viewports:
因此,对于 3 个不同的视口,您最终会得到如下结果:
<img style="display: none; height: auto; width:100%; background-image: url('img/1078x501_1.jpg'); background-size: cover;" class="center-block visible-lg-block" src="img/400x186_trans.png" alt="pic 1">
<img style="display: none; height: auto; width:100%; background-image: url('img/517x240_1.jpg'); background-size: cover;" class="center-block visible-md-block" src="img/400x186_trans.png" alt="pic 1">
<img style="display: none; height: auto; width:100%; background-image: url('img/400x186_1.jpg'); background-size: cover;" class="center-block visible-sm-block" src="img/400x186_trans.png" alt="pic 1">
And only your default media viewport size images load during the initial load, then afterwards, depending on your viewport, images will dynamically load.
并且仅在初始加载期间加载默认媒体视口大小的图像,然后根据您的视口,图像将动态加载。
And no javascript!
而且没有javascript!