手写现代前端框架diff算法-前端面试进阶
前言
在前端工程上,日益复杂的今天,性能优化已经成为必不可少的环境。前端需要从每一个细节的问题去优化。那么如何更优,当然与他的如何怎么实现的有关。比如key为什么不能使用index呢?为什么不使用随机数呢?答案当然是影响性能,那为什么?相信你看完本文的diff算法就能略懂一些。
diff算法的概念
diff算法, 是 Virtual DOM 产生的一个概念, 作用是用来计算出 Virtual DOM 中被改变的部分,然后根据算法算出dom的结果进行原生DOM操作,而不用重新渲染整个页面,从而提高了页面渲染效率,已经成为当今框架(vue,react)必不可少的部分。
手写diff算法的过程
背景:dom对性能的消耗特别高,因此前辈们提出用js对象模拟dom的操作,计算出最后需要更新的部分。而dom本身的算法的时间复杂度是O(n ^ 3)。这时react团队,提出了diff算法!(本案例提供核心代码,以及完整案例)
简单理解版本的思路的核心,可分为三个步骤:
1.模拟"dom树",将dom转换为js数组。
定义js构造函数,可同步dom对象。通常对象可由下边组成:tag('string'):标签的名称props('object'):属性与属性的值{ class: 'a', type: 'hidden'}children('array'):子属性key('string'):表示元素的唯一标识 'nowKeys'
2.获取两个dom数之间的差异(diff算法)
对比两个dom对应的实体,获取他们的不同点,根据顺序数组。当前demo处理了以下方法:
Change: 'Change',//表示元素有变化Move: 'Move',//表示移动了位置Add: 'Add',//表示元素是新增的Del: 'Del',//表示元素给删除了DiffPropsList: 'DiffPropsList',//表示元素对应的属性列表有变动DelProps: 'DelProps',//表示该属性给删除ChangeProps: 'ChangeProps',//表示该属性有变化AddProps: 'AddProps',//表示该属性是新增的
3.将“差异”进行“渲染”
根据步骤2),将差异进行对应的处理
实例方法如下:
var a1 =new WzElement('div', { class: 'a1Class' }, ['a1'], "a1");
var a2 =new WzElement('div', { class: 'a2Class' }, ['a2'], "a2")
let root = a1.render();//js模拟dom生成
步骤2)
let pathchs = diff(a1, a2); //获取当前的两个dom的差异
步骤3)
reloadDom(root, pathchs);//根据差异重新渲染
核心的代码(步骤1):
_createDom( tag, props, children, key ){let dom = document.createElement( tag );for( let propKey in props ){dom.setAttribute( propKey, props[propKey] );}if( !key ){dom.setAttribute( "key", key );}children.forEach( item => {if( item instanceof WzElement ){//var root = this._createDom(item.tag,item.props,item.children,item.key)dom.appendChild( root ); }else{var childNode = document.createTextNode( item );dom.appendChild( childNode ); }});return dom;}
核心的代码(步骤2):参考 前端进阶面试题详细解答
//判断当前对象
function dfs(oldElement, newElement, index, patches) {//如果新的对象为空,无需要对比//如果新的对象,key跟tag都不同,说明元素变了,直接替换。//如果新的对象,key跟tag都相同,则遍历子集,观察子集是否不同,观察元素属性是否不同var curPatches = [];if (!newElement) {} else if (oldElement.key != newElement.key || oldElement.tag != newElement.tag) {curPatches.push({type: stateType.Change,node: newElement});} else {var propsDiff = diffProps(oldElement.props, newElement.props);if (propsDiff.length > 0) {curPatches.push({type: stateType.DiffPropsList,node: newElement});}diffChildren(oldElement.children, newElement.children,index, patches);//对比子集是否不同}if (curPatches.length > 0) {if (!patches[index]) {patches[index] = []}patches[index] = patches[index].concat(curPatches);}return patches;
}//对比子集是否不同
function diffChildren(oldChild, newChild, index, patches) {let { changeList, resultList } = listDiff(oldChild, newChild, index, patches);if (changeList.length > 0) {if (!patches[index]) {patches[index] = []}patches[index] = patches[index].concat(changeList);}let last = null;oldChild && oldChild.forEach((item, i) => {let child = item && item.children;if (child) {if ( last && last.children != null) {//有子节点index = index + last.children.length + 1;} else {index += 1;}let keyIndex = resultList.indexOf( item.key ) ;let node = newChild[keyIndex]//只遍历新旧中都存在的节点,其他新增或者删除的没必要遍历if ( node ) {dfs(item, node, index, patches)}} else {index += 1;}last = item});
}
核心的代码(步骤3):
var num = 0;
//根据virtDom的结果渲染页面
function reloadDom( node, patchs ){var changes = patchs[ num ];let childNodes = node && node.childNodes;if (!childNodes) num += 1if( changes != null ){changeDom( node, changes );}//保持更diff算法的num一直var last = nullchildNodes && childNodes.forEach(( item, i ) => {if( childNodes ){if ( last && last.children != null) {//有子节点num = num + last.children.length + 1;} else {num += 1;}}reloadDom( item, patchs );last = item;})
}//执行每个dom的变化
function changeDom( node, changes ){changes && changes.forEach( change => {let {type} = change;switch( type ){case stateType.Change:node.parentNode && node.parentNode.replaceChild( change.node.create() , node );break;case stateType.Move:let fromNode = node.childNodes[change.from];let toNode = node.childNodes[change.to];let formClone = fromNode.cloneNode(true);let toClone = toNode.cloneNode(true);node.replaceChild( fromNode, toClone ) ;node.replaceChild( toNode, formClone ) ;break;case stateType.Add:node.insertBefore( change.node.create(), node.childNodes[ change.index ] )break;case stateType.Del:node.childNodes[change.index ].remove();break;case stateType.DiffPropsList:let {props} = change.node;for( let key in props ){if( key == stateType.DelProps ){node.removeAttribute( );} else {node.setAttribute( key, props[key] );}}break;default:break;}});
}