对于我目前使用 style.css 和一堆其他样式表、960.css 等的网站,加载如下:
<link rel="stylesheet" media="screen" href="css/style.css">
<link rel="stylesheet" media="only screen and (max-width: 960px)" href="css/960.css">
....
现在我关心的是速度。我知道我可以将这些文件合并成一个大文件,但这意味着还要下载不相关的数据。
基本上,我的问题是:什么是更好的方法,最小化请求量,或最小化传递给一个用户的数据量?
最佳答案
在合理的速度链接上,额外请求中涉及的延迟和开销可能会超过不下载少量(希望缩小和 gzip 压缩)文本数据的 yield ,而这些文本数据对于该用户来说仍然不需要以该分辨率显示页面。参见 Ilya Grigorik 的 excellent post on latency有关这如何被证明是许多用户的主要性能限制的更多详细信息。
额外数据的延迟成本对于使用移动设备的用户尤其如此(移动设备在不使用时会节省 radio 的电量),对于建立成本相对较高的移动 2G 或 3G 连接更是如此连接(4G 显然大大改善了这一点)。
与所有这些事情一样,关键是测试和测量 - 但我几乎可以肯定地希望捆绑样式对您的用户来说会更快。不要忘记每个有效的样式表 ( where the media query evaluates to true ) 都会阻止页面的呈现。
同样值得注意的是 Ilya(他在 Google 工作,所以应该知道)引用 WebKit 仍会下载返回 false 的样式表媒体查询,尽管优先级较低且处于非阻塞状态方式。
if the media query evaluates to false then the stylesheet is marked as NonBlocking and is given a very low download priority
和
The only caveat, as Scott indicates, is that the browser will download all enabled stylesheets, even though the screen on your device may not ever exceed the [cited] width
简要查看 webkit 源代码,它似乎仍然会发生这种情况,大概是为了允许即时响应屏幕旋转或窗口大小调整。
// Load stylesheets that are not needed for the rendering immediately with low priority.
223 ResourceLoadPriority priority = isActive ? ResourceLoadPriorityUnresolved : ResourceLoadPriorityVeryLow;
224 CachedResourceRequest request(ResourceRequest(document().completeURL(url)), charset, priority);
225 request.setInitiator(this);
226 m_cachedSheet = document().cachedResourceLoader()->requestCSSStyleSheet(request);
对于这样的问题我强烈推荐High Performance Browser Networking您可以免费在线阅读。
关于html - CSS媒体查询: one file vs.分离文件及对加载速度的影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20629980/