很多web开发者都已经意识到,在脚本执行中,DOM操作的用时可能比js本身执行时间要长很多,其中潜在的消耗基本上是由于触发了layout(即重排reflow:由DOM树构建为Render渲染树的过程),DOM结构越大越复杂,则操作的代价越昂贵。

目前一个保持页面敏捷快速的比较重要的技巧就是将对dom的不同操作合并在一起,然后批量一次性改变dom的结构状态,比如:

// 不推荐的方式,会引起两次重排(layout)
var newWidth = aDiv.offsetWidth + 10; // 读取
aDiv.style.width = newWidth + 'px'; // 更新样式
var newHeight = aDiv.offsetHeight + 10; // 读取
aDiv.style.height = newHeight + 'px'; // 更新样式 // 推荐,仅触发1次重排
var newWidth = aDiv.offsetWidth + 10; // 读取
var newHeight = aDiv.offsetHeight + 10; // 读取
aDiv.style.width = newWidth + 'px'; // 更新
aDiv.style.height = newHeight + 'px'; // 更新

Stoyan Stefanovtome on repaint, relayout and restyle这篇文章已对此作出了非常精彩的解释。

由此,经常会有人问:到底什么会触发layout?Dimitri Glazkov 在此回答了这个问题。便于我自己理解,我将这些会导致layout的DOM的属性和方法弄成了一个列表,如下:

Element

clientHeight, clientLeft, clientTop, clientWidth, focus(), getBoundingClientRect(), getClientRects(), innerText, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerText, scrollByLines(), scrollByPages(), scrollHeight, scrollIntoView(), scrollIntoViewIfNeeded(), scrollLeft, scrollTop, scrollWidth

Frame, Image

height, width

Range

getBoundingClientRect(), getClientRects()

SVGLocatable

computeCTM(), getBBox()

SVGTextContent

getCharNumAtPosition(), getComputedTextLength(), getEndPositionOfChar(), getExtentOfChar(), getNumberOfChars(), getRotationOfChar(), getStartPositionOfChar(), getSubStringLength(), selectSubString()

SVGUse

instanceRoot

window对象

getComputedStyle(), scrollBy(), scrollTo(), scrollX, scrollY, webkitConvertPointFromNodeToPage(), webkitConvertPointFromPageToNode()

列表并不完善,但算是一个开始吧,其实最好的方式,当然是在Timeline工具中去分析瓶颈。

 
 

最新文章

  1. AI人工智能系列随笔:syntaxnet 初探(1)
  2. Http 和TCP的关系,TCP长连接和短连接有什么区别?
  3. ACM: 限时训练题解- Travelling Salesman-最小生成树
  4. 运用CSS和JS写的大图轮播-带箭头
  5. TextView的一些高级应用(自定义字体、显示多种颜色、添加阴影)
  6. esc安装数据库 sqlserver mssql
  7. [安卓]AndroidManifest.xml文件简介及结构
  8. webServer xampp的安装及使用
  9. Android 开源项目DiskLruCache 详解
  10. 20+ Rsync command’s switches and common usages with examples – Unix/Linux--reference
  11. HDOJ/HDU 2352 Verdis Quo(罗马数字与10进制数的转换)
  12. openerp binary filed import export
  13. JQuery语法总结和注意事项
  14. Android存储之SQLiteDatbase
  15. SharePoint2013 Excel导出好的代码
  16. Javascript中alert</script>的方法
  17. json转javascript对象
  18. nopCommerce 3.9 大波浪系列 之 使用Redis主从高可用缓存
  19. Visual Studio 我的插件
  20. Python-Blog1-搭建开发环境

热门文章

  1. SQL语句新建数据库
  2. 7. ENGINES
  3. MariaDB数据库(二)
  4. tornado框架基础02-输入和输出
  5. STM32F407 独立看门狗 个人笔记
  6. POJ1703-Find them, Catch them 并查集构造
  7. 【Kubernetes】Kubernetes删除namespace后持续terminating状态
  8. 【二分贪心+精度问题】F. Pie
  9. [NOIP1998] 提高组 洛谷P1011 车站
  10. SGU 104 Little shop of flowers【DP】