每个响应式网站开发教程都建议使用display:none CSS属性来隐藏移动浏览器加载的内容,这样网站加载得更快。这是真的吗?display:none不加载图像,还是在移动浏览器上加载内容?有没有什么方法可以防止在移动浏览器上加载不必要的内容?
当前回答
为了防止获取资源,使用Web Components的<template>元素。
其他回答
是的,它会渲染得更快一点,只是因为它不需要渲染图像,并且在屏幕上少了一个元素来排序。
如果您不想加载它,请将DIV保留为空,以便稍后加载包含<img>标记的html。
尝试使用firebug或wireshark,就像我之前提到的那样,你会看到即使display:none存在,文件也会被传输。
Opera是唯一一个在显示设置为none时不加载图像的浏览器。Opera现在已经转移到webkit,即使它们的显示设置为none,也会渲染所有图像。
这里有一个测试页面可以证明这一点:
http://www.quirksmode.org/css/displayimg.html
答案不像简单的是或不是那么简单。看看我最近做的一个测试的结果:
在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.
嗨,伙计们,我也在与同样的问题作斗争,如何不在移动设备上加载图像。
但我想到了一个好办法。首先创建一个img标签,然后在src属性中加载一个空白的svg。现在,您可以将图像的URL设置为内联样式的content: URL('链接到您的图像');。现在用你选择的包装包装你的img标签。
<div class="test">
<img src="data:image/svg+xml,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22/%3E" style="content:url('https://blog.prepscholar.com/hubfs/body_testinprogress.gif?t=1495225010554')">
</div>
@media only screen and (max-width: 800px) {
.test{
display: none;
}
}
将包装器设置为在不希望加载图像的断点上不显示任何内容。img标记的内联css现在被忽略,因为包装器中没有显示的元素的样式将被忽略,因此图像不会被加载,直到到达包装器有显示块的断点。
好了,在移动断点上不加载img的简单方法:)
查看这个代码依赖,以获得一个工作示例:http://codepen.io/fennefoss/pen/jmXjvo
如果是这样,有没有一种方法不加载不必要的内容在手机上 浏览器吗?
使用<img src="" srcset="">
http://www.webdesignerdepot.com/2015/08/the-state-of-responsive-images/
https://caniuse.com/#feat=srcset
另一种可能是使用<noscript>标记,并将图像放在<noscript>标记中。然后使用javascript删除noscript标签,因为你需要的图像。通过这种方式,您可以使用渐进增强按需加载图像。
使用我写的这个polyfill来读取IE8中<noscript>标签的内容
https://github.com/jameswestgate/noscript-textcontent