每个响应式网站开发教程都建议使用display:none CSS属性来隐藏移动浏览器加载的内容,这样网站加载得更快。这是真的吗?display:none不加载图像,还是在移动浏览器上加载内容?有没有什么方法可以防止在移动浏览器上加载不必要的内容?
当前回答
我们说的是图像不能在手机上加载,对吧?那么如果你只是做一个@media (min-width: 400px){background-image:thing.jpg}
那么,它难道不会只寻找超过一定屏幕宽度的图像吗?
其他回答
怪癖模式:图像和显示:无
当图像有显示时:none或在元素with中 Display:none,浏览器可能会选择在显示之前不下载图像 设置为另一个值。 当您将显示切换为block时,只有Opera才能下载图像。 所有其他浏览器立即下载它。
答案不像简单的是或不是那么简单。看看我最近做的一个测试的结果:
在Chrome浏览器:所有8个截图-*图像加载(img 1) 在Firefox中:仅加载当前正在显示的1个截图*图像(img 2)
所以在深入挖掘之后,我发现了这个,这解释了每个浏览器如何处理加载基于css显示的img资产:none;
摘自博客文章:
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.
我们说的是图像不能在手机上加载,对吧?那么如果你只是做一个@media (min-width: 400px){background-image:thing.jpg}
那么,它难道不会只寻找超过一定屏幕宽度的图像吗?
如果你让图片成为CSS中一个div的背景图片,当这个div被设置为“display: none”时,图片将不会被加载。当CSS被禁用时,它仍然不能加载,因为CSS是禁用的。
使用@media query CSS,基本上我们只是发布了一个项目,我们在桌面上有一个巨大的树的图像,但没有显示在桌面/移动屏幕上。所以防止图像加载非常简单
下面是一个小片段:
.tree {
background: none top left no-repeat;
}
@media only screen and (min-width: 1200px) {
.tree {
background: url(enormous-tree.png) top left no-repeat;
}
}
你可以使用相同的CSS来显示和隐藏显示/可见/不透明度,但图像仍在加载,这是我们想出的最安全的代码。