html - CSS媒体查询: one file vs.分离文件及对加载速度的影响

标签 html css performance optimization bandwidth

对于我目前使用 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/

相关文章:

python - Python/Selenium 中查询链接打印错误

html - 如何在子div之间划分父div的高度

html - 文本阴影 CSS 无法正常工作

python - 更多的标题困惑。为什么信号量这么慢?

r - 提升 ggplot2 性能

python - 将大数据作为函数参数传递时python的性能

javascript - jQuery scrolling 随机滚动

html - 除第一行外,所有行均相同

jquery - 将 child 的类(class)添加到 parent

css - 样式化 'first-line' 内部元素