防止Bootstrap预加载所有hidden-*图像

Her*_*key 5 css image responsive-design twitter-bootstrap

我正在运行Twitter Bootstrap 3.2.

我的页面有每个断点的横幅图像.这意味着代码如下:

<img class="visible-xs img-responsive" src="headline-768px.jpg">   (128kb)
<img class="visible-sm img-responsive" src="headline-992px.jpg">   (144kb)
<img class="visible-md img-responsive" src="headline-1200px.jpg">  (264kb)
<img class="visible-lg img-responsive" src="headline-2000px.jpg">  (380kb)
Run Code Online (Sandbox Code Playgroud)

拥有4个不同图像的主要目的是使移动设备不需要下载更大的版本.但无论屏幕大小如何,Bootstrap都会预加载所有版本,即使它们隐藏在当前断点处.对于每个观看者来说,这相当于数百个不必要的kb.

有没有解决的办法?

Kyl*_*Mit 8

演示问题:

并非所有浏览器都有相同的反应,但通常浏览器会从src属性加载内容,无论其他CSS规则是否将该元素呈现为不可见.

这是一个基线示例:

<img class="visible-xs img-responsive" src="http://placehold.it/768x150" />
<img class="visible-sm img-responsive" src="http://placehold.it/992x150" />
<img class="visible-md img-responsive" src="http://placehold.it/1200x150"/>
<img class="visible-lg img-responsive" src="http://placehold.it/2000x150"/>
Run Code Online (Sandbox Code Playgroud)

在jsFiddle演示

每当我刷新页面时,浏览器都会加载所有图像,甚至是最初不可见的图像:

负载所有

背景图像+媒体查询

有关CSS背景图像的简单响应图像的教程更深入,但基本解决方案的工作方式如下:

创建一个简单的div:

<div class="responsiveBackgroundImage" id="myImage" ></div>
Run Code Online (Sandbox Code Playgroud)

然后根据屏幕尺寸选择正确的背景图像:

我们可能希望所有背景图像共享一些基本属性,如下所示:

.responsiveBackgroundImage { 
    width:100%;
    background-size: 100%;
    background-position: 50% 0%;
    background-repeat: no-repeat;
}   
Run Code Online (Sandbox Code Playgroud)

然后background-image在每个分辨率下替换此特定元素的属性:

#myImage {background-image: url(http://placehold.it/768x150); }
@media (min-width: 768px)  { #myImage { background-image: url(http://placehold.it/992x150); }}
@media (min-width: 992px)  { #myImage { background-image: url(http://placehold.it/1200x150);}}
@media (min-width: 1200px) { #myImage { background-image: url(http://placehold.it/2000x150);}}
Run Code Online (Sandbox Code Playgroud)

在jsFiddle演示

用Javascript替换图像

由于使用背景图像的限制,您可能决定使用真实img元素,然后只是动态加载图像.ng-src在评估解析为url的表达式时,您可以执行类似于angular所做的操作,而不是加载元素本身.当浏览器加载每个元素时,它将无法找到文件位置src="{{personImageUrl}}".相反,Angular将预期的URL保存为数据属性,然后在适当时加载.

首先,拍摄每个图像并为该src属性添加前缀data-.现在浏览器不会自动开始实现任何内容,但我们仍然可以使用这些信息.

<img class="visible-xs img-responsive" data-src="http://placehold.it/768x150"/>
Run Code Online (Sandbox Code Playgroud)

然后查询我们最终要加载的所有动态图像.

$dynamicImages = $("[data-src]");
Run Code Online (Sandbox Code Playgroud)

接下来,我们将要捕获窗口调整大小事件,并且在第一页加载时,我们将触发一个,以便我们可以使用相同的代码.使用这样的函数:

$(window).resize(function() {
    // Code Goes Here
}).resize();
Run Code Online (Sandbox Code Playgroud)

然后检查每个动态图像是否可见.如果是这样,从数据属性加载图像并将其从数组中删除,这样我们就不必继续检查和加载它.

$dynamicImages.each(function(index) {
    if ($(this).css('display') !== 'none') {
        this.src = $(this).data('src');
        $dynamicImages.splice(index, 1)
    }
});
Run Code Online (Sandbox Code Playgroud)

在jsFiddle演示


Luc*_*uca 2

它不是引导程序,而是浏览器。您应该将背景图像(而不是<img>标签)与媒体查询一起使用。

正确的浏览器只会加载与媒体查询匹配的 css 背景图像,但加载标记中的所有图像是有意义的,无论它们的 css 样式如何

(必要的痛苦直到<picture>得到广泛支持)