CSS性能问题 [英] CSS Performance Question

查看:96
本文介绍了CSS性能问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道专家在编写CSS代码时做了什么。是不是使用tagname.className样式?继承是否导致明显的性能损失?它只影响浏览器加载页面时或以后?例如:用户进一步向下滚动页面,当查看具有大量结果的页面时,不良的CSS是否会导致缓慢的滚动?

I was wondering what the experts do when it comes to writing CSS code. Is it bad to use the tagname.className style? Does inheritance cause a noticeable performance loss? Does it only affect the browser when loading a page or also after? eg: user scrolls down further the page, would poor CSS be a culprit to sluggish scrolling when viewing a page with a lot of rows of results?

CSS示例:

div.result-row{...}
div.result-row div.photo-column{...}
div.result-row div.main-column{...}
div.result-row div.main-column div.text-row{}
div.result-row div.main-column div.date-row{}
div.result-row div.action-column{...}

vs

div.result-row{...}
div.photo-column{...}
div.main-column{...}
div.action-column{...}
div.text-row{...}
div.date-row{...}

我的页面输出很多的用户帖子,像这样...

My page is outputting a lot of user posts like this...

<div class="result-row clearfix">
    <div class="photo-column">
        <img src="..." />
    </div>
    <div class="main-column">
        <div class="text-row">
            User's text
        </div>
        <div class="date-row">
            Today
        </div>
    </div>
    <div class="action-column">
        <a href="#">...</a>
        <a href="#">...</a>
    </div>
</div>


推荐答案

Google Page Speed 有一个有关使用高效的CSS选择器。它提到了后代选择器是如何低效的,因为一旦最右边的选择器已经匹配浏览器必须[也]遍历DOM树,评估每个祖先元素,直到找到匹配或到达根元素。 Mozilla甚至说后代选择器是CSS中最昂贵的选择器。因此, code> div.photo-column {...} 会优先于 div.result-row div.photo-column {...}

The documentation for Google's Page Speed has a section about using efficient CSS selectors. It mentions how descendant selectors are inefficient because once the rightmost selector has been matched "the browser must [also] traverse up the DOM tree, evaluating every ancestor element until it finds a match or reaches the root element." Mozilla even says "the descendant selector is the most expensive selector in CSS." So div.photo-column{...} would be preferable to div.result-row div.photo-column{...}.

它还提到你应该删除冗余限定符,如由标签选择器限定的类选择器(当一个类只用于一个标签时,这是一个好的设计实践无论如何)。这是有道理的,因为如果你有 div.photo-column {...} 而不是 .photo-column {...} 浏览器必须进行两次检查,一个检查class =photo-column,如果这是真的,一个检查元素是否是一个div,而不是只检查类,如果这是全部您指定。

It also mentions that you should remove redundant qualifiers such as "class selectors qualified by tag selectors (when a class is only used for one tag, which is a good design practice anyway)." That makes sense because if you have div.photo-column{...} instead of .photo-column{...} the browser has to make two checks, one to check for class="photo-column" and, if that's true, one to check if the element is a div, rather than just checking for the class, if that's all you specify.

这篇关于CSS性能问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆