var $body = $('body'); $body.css('padding', '1px'); $body.css('padding'); // reading a property, a forced reflow $body.css('color', 'red'); $body.css('margin', '2px'); 其结果就是,重排发生了两次。因此,你应该把访问元素属性的操作都组织在一起,从而优化网页性能。(你可以在JSBin查到更为详细的例子) 有时,你必须触发一个强制性重排。比如,我们必须将同样的属性(比如左边距)两次赋值给同一个元素。起初,它应该设置为100px,且不带动效。接着,它必须通过过渡(transition)动效改变为50px。你现在可以在JSbin上学习这个例子,不过我会在这儿更详细地介绍它。 首先,我们创建一个带过渡效果的CSS类:.has-transition { -webkit-transition: margin-left 1s ease-out; -moz-transition: margin-left 1s ease-out; -o-transition: margin-left 1s ease-out; transition: margin-left 1s ease-out; } 然后继续执行:// our element that has a "has-transition" class by default var $targetElem = $('#targetElemId'); // remove the transition class $targetElem.removeClass('has-transition'); // change the property expecting the transition to be off, as the class is not there // anymore $targetElem.css('margin-left', 100); // put the transition class back $targetElem.addClass('has-transition'); // change the property $targetElem.css('margin-left', 50);然而,这个执行无法奏效。所有改变都被缓存,只在代码块末尾加以执行。我们需要的是强制性的重排,我们可以通过以下更改加以实现: // remove the transition class $(this).removeClass('has-transition'); // change the property $(this).css('margin-left', 100); // trigger a forced reflow, so that changes in a class/property get applied immediately $(this)[0].offsetHeight; // an example, other properties would work, too // put the transition class back $(this).addClass('has-transition'); // change the property $(this).css('margin-left', 50);现在代码如预期那样执行了。 有关性能优化的实际建议 总结现有的资料,我提出以下建议: 创建有效的HTML和CSS文件,不要忘记指明文档的编码方式。样式应该包含在标签内,脚本代码则应该加在标签末端。 尽量简化和优化CSS选择器(这种优化方式几乎被使用CSS预处理器的开发者统一忽视了)将嵌套程度保持在最低水平。以下是CSS选择器的性能排名(从最快者开始) 1. 识别器:#id 2. 类:.class 3. 标签:div 4. 相邻兄弟选择器:a + i 5. 父类选择器:ul> li 6. 通用选择器:* 7. 属性选择:input[type="text"] 8. 伪类和伪元素:a:hover你应该记住,浏览器在处理选择器时依照从右到左的原则,因此最右端的选择器应该是最快的:#id或则.class:div * {...} // bad .list li {...} // bad .list-item {...} // good #list .list-item {...} // good * 1.在你的脚本代码中,尽可能减少DOM操作。缓存所有东西,包括元素属性以及对象(如果它们被重用的话)。当进行复杂的操作时,使用“孤立”元素会更好,之后可以将其加到DOM中(所谓“孤立”元素是与DOM脱离,仅保存在内存中的元素)。 2.如果你使用jQuery来选择元素,请遵从jQuery选择器最佳实践方案。 3.为了改变元素的样式,修改“类”的属性是奏效的方法之一。执行这一改变时,处在DOM渲染树的位置越深越好(这还有助于将逻辑与表象脱离)。 4.尽量只给位置绝对或者固定的元素添加动画效果。 5.在使用滚动时禁用复杂的悬停动效(比如,在中添加一个额外的不悬停类)。读者可以阅读关于这个问题的一篇文章。 想了解更多的细节问题,大家也可以看看这两篇文章: 1,How browsers work? 2,Rendering: repaint, reflow/relayout, restyle