您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息

如何使用CSS控制前端图片HTTP请求

2024/4/25 15:56:06发布5次查看
web前端图片加载的方式多种多样,其所产生的http请求也各异,这里我们就来列举css控制前端图片http请求的各种情况示例,需要的朋友可以参考下
图片的http请求,有很多种情况,那么究竟什么情况下面不会发生请求呢?下面我用案例一一列举一下,希望对你深入了解http图片请求有所帮助。
1. 隐藏图片
<img src="haorooms.jpg" style="display: none" />
http请求如下:
结论:只有opera不产生请求。 注意:用visibility: hidden隐藏图片时,在opera下也会产生请求。
2. 重复图片
<img src="haorooms.jpg" /><img src="haorooms.jpg" />
http请求如下:
结论:所有浏览器都只产生一次请求 。
3. 重复背景
<style type="text/css"> .test1 { background: url(haorooms.jpg) } .test2 { background: url(haorooms.jpg) } </style> <p class="test1">test1</p> <p class="test2">test2</p>
http请求如下:
结论:所有浏览器都只产生一次请求。
4. 不存在的元素的背景
<style type="text/css"> .test1 { background: url(haorooms.jpg) } .test2 { background: url(http2.jpg) } /* 页面中没有class为test2的元素 */</style> <p class="test1">test1</p>
http请求如下:
结论:背景仅在应用的元素在页面中存在时,才会产生请求。这对css框架来说,很有意义。
5. 隐藏元素的背景
<style type="text/css"> .test1 { background: url(haorooms.jpg); display: none; } .test2 { background: url(http2.jpg); visibility: hidden; } </style> <p class="test1">test1</p>
http请求如下:
结论:opera和firefox对于用display: none隐藏的元素背景,不会产生http请求。仅当这些元素非display: none时,才会请求背景图片。
6. 多重背景
<style type="text/css"> .test1 { background: url(haorooms.jpg); } .test1 { background: url(http2.jpg); } </style> <p class="test1">test1</p>
上面这段代码的http请求,只会请求http2.jpg这一张图片,原因是test1的class把上面的给覆盖掉了,所有只请求后面的一张图片!
假如用css3多张背景图片的写法:
<style type="text/css"> .test1 { background-image:url("haorooms.jpg"),url("http2.jpg"); } </style> <p class="test1">test1</p>
那么http请求如下:
webkit引擎浏览器对背景图都请求,是因为支持css3中的多背景图。
7. hover的背景加载
<style type="text/css"> a.test1 { background: url(haorooms.jpg); } a.test1:hover { background: url(http2.jpg); } </style> <a href="#" class="test1">test1</a>
http请求如下:
结论:触发hover时,才会请求hover状态下的背景。不触发的话,只请求默认的背景图片。
8. js里innerhtml中的图片
<script type="text/javascript"> var el = document.createelement('p'); el.innerhtml = '<img src="haorooms.jpg" />'; //document.body.appendchild(el); </script>
http请求如下:
结论:只有opera不会马上请求图片。
注意:当添加到dom树上时,opera才会发送请求。
9. 图片预加载
最常用的是js方案:
<script type="text/javascript"> new image().src = 'haorooms.jpg'; new image().src = 'http2.jpg'; </script>
在无js支持的环境下,可以采用隐藏元素来预加载:
<img src="haoroomscom.jpg" style="visibility: hidden; height: 0; width: 0" />
总结
1、对于隐藏图片和隐藏元素的背景,opera不会产生请求。
2、对于隐藏元素的背景,firefox也不会产生请求。
3、对于尚未插入dom树的img元素,opera不会产生请求。
4、基于webkit引擎的safari和chrome,支持多背景图。
5、其它情景,所有主流浏览器保持一致。
希望上面的图片http请求对您有所帮助,大家可以相互留言交流!
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注!
相关推荐:
关于css实现右侧固定宽度和左侧宽度的自适应方法
使用html和css实现康奈尔笔记的模板
以上就是如何使用css控制前端图片http请求的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录