每个响应式网站开发教程都建议使用display:none CSS属性来隐藏移动浏览器加载的内容,这样网站加载得更快。这是真的吗?display:none不加载图像,还是在移动浏览器上加载内容?有没有什么方法可以防止在移动浏览器上加载不必要的内容?
当前回答
使用@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来显示和隐藏显示/可见/不透明度,但图像仍在加载,这是我们想出的最安全的代码。
其他回答
** 2019回答**
在正常情况下显示:none不阻止图像被下载
/*will be downloaded*/
#element1 {
display: none;
background-image: url('https://picsum.photos/id/237/100');
}
但是如果一个祖先元素有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');
}
其他阻止下载映像的情况:
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-两个相等的类加载不同的图像
/* 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');
}
你可以在这里观看:https://codepen.io/juanmamenendez15/pen/dLQPmX
为了防止获取资源,使用Web Components的<template>元素。
不。如果您正在考虑节省手机用户带宽,图像将像往常一样加载,并且仍将使用用户的带宽。你能做的就是使用媒体查询和过滤你想要加载图像的设备。你的图像必须设置为一个div的背景图像等,而不是一个标签,因为图像标签将加载图像,无论屏幕大小和媒体查询设置。
浏览器似乎仍然下载图像,即使他们直接或间接隐藏的display: none属性。
我发现防止这种情况发生的唯一标准方法是使用img标签的loading属性:
<img src="https://cdn.test/img.jpg" loading="lazy">
除了Safari和Firefox Android,所有最新的浏览器都支持它。
MDN img加载属性规范。
另一种可能是使用<noscript>标记,并将图像放在<noscript>标记中。然后使用javascript删除noscript标签,因为你需要的图像。通过这种方式,您可以使用渐进增强按需加载图像。
使用我写的这个polyfill来读取IE8中<noscript>标签的内容
https://github.com/jameswestgate/noscript-textcontent