What happens when loading HTML
Reflux
When part or all of the render tree because of the size of the element size, layout, hide when other changes, the browser re-render part or all of DOM DOM process
Called reflux.
Redraw
The following cases will lead to reflow occurs:
1: to change the window size
2: change the text size
3: content changes, such as a user typing along in the box
4: active pseudo-class, such as: hover
. 5: operation class attribute
6: script operations the DOM
. 7: offsetWidth and calculating the offsetHeight
. 8 : setting style properties
How to optimize it?
1. Optimization Mechanism browser:
Modern browsers are very clever because every rearrangement will result in additional computational cost, so most browsers by modifying and queued batch execution to optimize the rearrangement process. Browser will modify the operation put into the queue, or until a period of time of operation reaches a threshold value, the queue was empty. but! When you get the layout of the operation information of the time, it will force the queue to refresh , such as when you visit the following properties or use the following method:
offsetTop、offsetLeft、offsetWidth、offsetHeight
scrollTop、scrollLeft、scrollWidth、scrollHeight
clientTop、clientLeft、clientWidth、clientHeight
getComputedStyle()
getBoundingClientRect
The above properties and methods need to return the most recent layout information, the browser has to empty the queue, triggering reflux redrawn to return the correct value . Therefore, we modify the style, it is best to avoid using the properties listed above, they will refresh render queue.
If we want to acquire and operate constantly these values, these values can be cached first example:
var windowHeight = window.innerHeight;//reflow
for(i=0;i<10;i++){
$body.height(windowHeight++);
一系列关于windowHeight的操作.......
}
2.自己的优化
靠浏览器不如靠自己,我们可以改变一些写法减少回流和重绘:
1:不要通过父级来改变子元素样式,最好直接改变子元素样式,改变子元素样式尽可能不要影响父元素和兄弟元素的大小和尺寸。
2:尽量通过class来设计元素样式,切忌用style。
3.对于复杂动画效果,使用绝对定位让其脱离文档流,否则会引起父元素及后续元素大量的回流。
4:不要用tables布局的另一个原因就是tables中某个元素一旦触发reflow就会导致table里所有的其它元素reflow。在适合用table的场合,可以设置table-layout为auto或fixed.
5.避免设置多层内联样式.
6.使用修改样式cssText.
cssText 本质是什么?
cssText 的本质就是设置 HTML 元素的 style 属性值。
cssText 怎么用?
document.getElementById("d1").style.cssText = "color:red; font-size:13px;";
cssText 返回值是什么?
在某些浏览器中(比如 Chrome),你给他赋什么值,它就返回什么值。在 IE 中则比较痛苦,它会格式化输出、会把属性大写、会改变属性顺序、会去掉最后一个分号,比如:
1
2
|
document.getElementById( "d1" ).style.cssText = "color:red; font-size:13px;" ;
alert(document.getElementById( "d1" ).style.cssText);
|
在 IE 中值为:FONT-SIZE: 13px; COLOR: red
js中有一个cssText的方法:
语法为:
obj.style.cssText=”样式”;
element.style.cssText=”width:20px;height:20px;border:solid 1px red;”
为了解决这个问题,可以采用cssText累加的方法
Element.style.cssText += ‘width:100px;height:100px;top:100px;left:100px;’
Element.style.cssText += ‘;width:100px;height:100px;top:100px;left:100px;’