未使用的 CSS 图像是否已下载?

未使用的 CSS 图像是由浏览器下载还是被忽略?

例如,在 CSS 规则中不匹配任何元素。

.nothingHasThisClass{background:url(hugefile.png);}

或者这是依赖于浏览器的?

11102 次浏览

一个快速的测试证明了这一点。

<!DOCTYPE html>
<html>
<head>
<title></title>


<style type="text/css"><!--


.hasnothing{background-image:url(http://25.media.tumblr.com/tumblr_ky7aakqvH01qatluqo1_400.jpg);}
.hassomething{background-image:url(http://27.media.tumblr.com/tumblr_kxytwr7YzH1qajh4xo1_500.png);}


--></style>


</head><body>


<div class="hassomething"></div>


</body></html>

第二张图片 tumblr_kxytwr7YzH1qajh4xo1_500.png被下载了,但是没有下载另一张。这在 Chrome (开发工具)和 Firefox (Firebug)中被证明是正确的。

不,它们没有被下载,至少在 Firefox,IE8和 Chrome 中没有。

一个简单的测试方法:

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.nonexistent {
background: url('index.php?foo');
}
</style>
</head>
<body>
<?php if(isset($_GET['foo'])) {
file_put_contents('test.txt', $_SERVER['HTTP_USER_AGENT']);
} ?>
</body>
</html>

如果用浏览器的用户代理填充了 test.txt,则将下载图像。我的测试结果都不是这样。

Firefox 和 Chrome (Ubuntu 9.10)不会下载没有应用在 DOM 中的类/id 的图片。

但是,这两个平台可能都依赖于 还有浏览器。

这将取决于浏览器,因为他们决定如何实现规范,但在这里的一个快速测试:

  • Chrome: 没有
  • 火狐: 没有
  • Safari: 没有
  • IE8: 没有
  • IE7: 没有
  • IE6: 未知(有人能测试和评论吗?)

几乎所有的浏览器都进行延迟加载。如果不需要映像,则不下载。使用 firebug (Firefox/Chrome 中的插件)查看资源的加载时间。

有趣的是,Chrome (至少)会在下面的例子中下载 unused.png:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>test</title>
<style type="text/css">
.unused {
background: url(unused.png) no-repeat;
}
.used {
background: url(used.png);
}
</style>
</head>
<body>
<div class="unused used">
hello world
</div>
</body>
</html>

有时候,这完全取决于“未使用”是什么意思。不同的浏览器有不同的定义。例如,在 Firefox 中,应用到 <noscript>标签的样式被视为“未使用”,因此,任何图像都不会被下载。

Chrome26(可能是所有的,不确定) ,是的下载 CSS 图像,如果它们被应用到 <noscript>元素,甚至当 JS 被启用。(不过,我不是很清楚为什么,也许这是一个错误?).

它下载应用于元素 内心的 CSS 图像,尽管是 <noscript>元素。(当然,这是预期的行为)。

例如:

CSS:

noscript { background-image: url('always.png') 0 0 repeat; }
noscript p ( background-image: url('nojsonly.png') 0 0 repeat; }

HTML:

<noscript>The CSS background image of this NOSCRIPT-element will always be downloaded in Chrome.  Will not be downloaded in Firefox</noscript>
<noscript><p>The CSS background image of this P-element won't be downloaded in Chrome or other browsers, unless JS is disabled</p></noscript>

在这种情况下,如果用户启用了 JS,那么将在 Chrome 中下载 都有 always.png 和 other bg.png。如果用户启用了 JS,那么 Chrome 中只下载了 nojsonly.png。

我使用这种技术来测量非 JS 用户的流量水平,因为 Google Analytics 在这里让我们失望了。我更喜欢使用背景的 CSS 图像而不是一个正常的 <img...>标签,因为我的工作在(未经测试)的理论下,机器人不太可能抓取一个 CSS 图像比一个 <img...>图像,为人类访问者留下更准确的计数。