Vue核心之虚拟DOM以及diff算法的实现

第一次看前端知识的源码,相对于之前的学习难度提升了很多。不过也理解了很多有意思的东西!

js操作真实DOM的代价

用我们传统的开发模式,原生JS或JQ操作DOM时,浏览器会从构建DOM树开始从头到尾执行一遍流程。在一次操作中,我需要更新20个DOM节点,浏览器收到第一个DOM请求后并不知道还有19次更新操作,因此会马上执行流程,最终执行20次。例如,第一次计算完,紧接着下一个DOM更新请求,这个节点的坐标值就变了,前一次计算为无用功。计算DOM节点坐标值等都是白白浪费的性能。即使计算机硬件一直在迭代更新,操作DOM的代价仍旧是昂贵的,频繁操作还是会出现页面卡顿,影响用户体验。

虚拟DOM的优势

虚拟DOM就是为了解决浏览器性能问题而被设计出来的。如前,若一次操作中有10次更新DOM的动作,虚拟DOM不会立即操作DOM,而是将这10次更新的diff内容保存到本地一个JS对象中,我们也习惯的称之为补丁包patch,最终将这个JS对象一次性attch到DOM树上,再进行后续操作,避免大量无谓的计算量。所以,用JS对象模拟DOM节点的好处是,页面的更新可以先全部反映在JS对象(虚拟DOM)上,操作内存中的JS对象的速度显然要更快,等更新完成后,再将最终的JS对象映射成真实的DOM,交由浏览器去绘制。

js模拟虚拟DOM

Element方法返回值是一个虚拟的类似于DOM结构的树。

 var vdom = Element({
            tagName: 'ul',
            props: {
                'class': 'list'
            },
            children: [
                Element({
                    tagName: 'li',
                    children: ['item1']
                }),
                Element({
                    tagName: 'li',
                    children: ['item2']
                }),
                'hello,world'

            ]
        });

Element方法实现的源码

  function Element({
            tagName,
            props,
            children
        }) {
            //this本来是window,在这调用后就变成了这个构造函数的实例
            if (!(this instanceof Element)) {
                //返回一个构造函数并且重新执行这个函数。
                return new Element({
                    tagName,
                    props,
                    children
                })
            }
            this.tagName = tagName;
            this.props = props || {};
            this.children = children || [];
        }

接下来我们的工作就是把虚拟的DOM映射为真实的DOM结构

  Element.prototype.render = function() {
            var el = document.createElement(this.tagName),
                //在这里没有解构赋值
                props = this.props,
                propName,
                propValue;
            for (propName in props) {
                propValue = props[propName];
                el.setAttribute(propName, propValue);
            }
            this.children.forEach(function(child) {
                var childEl = null;
                //判断数组的子元素是否时我们创建的元素节点
                if (child instanceof Element) {
                    childEl = child.render();
                } else {
                    //如果不是则直接创建文本节点
                    childEl = document.createTextNode(child);
                }
                el.appendChild(childEl);
            });
            return el;
        };
        document.querySelector('#root').appendChild(vdom.render());

到这里我们已经完成了创建虚拟DOM并将其映射成真实DOM,这样所有的更新都可以先反应到虚拟DOM上,如何反应?需要用到Diff算法。Diff算法也算是虚拟DOM的核心内容了

虚拟DOM之Diff算法

在实际代码中,Diff算法会对新旧两棵树进行一个深度的遍历每个节点都会有唯一的一个标记。每遍历到一个节点就把该节点和新的树进行对比,如果有差异就记录到一个补丁对象patch中。
在这里插入图片描述
底下这段代码是我拷贝老师的,旁边的注释是对源码的理解。

diff.js的实现

这段代码快返回的结果就是补丁包patch,对象里面的成员的属性名就是我们上面所作的标记,也就是索引。

  // diff 函数,对比两棵树
        function diff(oldTree, newTree) {
            var index = 0 // 当前节点的标志
            var patches = {} // 用来记录每个节点差异的对象
            dfsWalk(oldTree, newTree, index, patches)
            return patches
        }

        // 对两棵树进行深度优先遍历
        function dfsWalk(oldNode, newNode, index, patches) {
            var currentPatch = []
            //如果测出的节点类型是字符串,我们认为是文本节点,不相等将新节点插入即可。
            if (typeof(oldNode) === "string" && typeof(newNode) === "string") {
                // 文本内容改变
                if (newNode !== oldNode) {
                    currentPatch.push({
                        type: patch.TEXT,
                        content: newNode
                    })
                }
            } else if (newNode != null && oldNode.tagName === newNode.tagName && oldNode.key === newNode.key) {
                // 节点相同,比较属性
                var propsPatches = diffProps(oldNode, newNode)
                if (propsPatches) {
                    currentPatch.push({
                        type: patch.PROPS,
                        props: propsPatches
                    })
                }
                // 比较子节点,如果子节点有'ignore'属性,则不需要比较
                if (!isIgnoreChildren(newNode)) {
                    diffChildren(
                        oldNode.children,
                        newNode.children,
                        index,
                        patches,
                        currentPatch
                    )
                }
            } else if (newNode !== null) {
                // 新节点和旧节点不同,用 replace 替换
                currentPatch.push({
                    type: patch.REPLACE,
                    node: newNode
                })
            }
           //判断我们临时的补丁包里面是否有值,如果有,说明新旧节点不同,则得加入到patch包里面
            if (currentPatch.length) {
                patches[index] = currentPatch
            }
        }
        
    function diffChildren(oldChildren, newChildren, index, patches, currentPatch) {
            var diffs = listDiff(oldChildren, newChildren, 'key')
            newChildren = diffs.children
            
            if (diffs.moves.length) {
                var reorderPatch = {
                    type: patch.REORDER,
                    moves: diffs.moves
                }
                currentPatch.push(reorderPatch)
            }

            var leftNode = null
            var currentNodeIndex = index
            _.each(oldChildren, function(child, i) {
                var newChild = newChildren[i]
                //给子节点加上标记
                currentNodeIndex = (leftNode && leftNode.count) ?
                    currentNodeIndex + leftNode.count + 1 :
                    currentNodeIndex + 1
                 //深度遍历子节点
                dfsWalk(child, newChild, currentNodeIndex, patches)
                leftNode = child
            })
        }
        
  function diffProps(oldNode, newNode) {
            var count = 0
            var oldProps = oldNode.props
            var newProps = newNode.props

            var key, value
            var propsPatches = {}

            // 判断如果新节点中的属性不等于旧节点,则将其记录在propsPatches这个对象中,返回出去
            for (key in oldProps) {
                value = oldProps[key]
                if (newProps[key] !== value) {
                    count++
                    propsPatches[key] = newProps[key]
                }
            }

            //如果老节点中没有这个属性的操作
            for (key in newProps) {
                value = newProps[key]
                if (!oldProps.hasOwnProperty(key)) {
                    count++
                    propsPatches[key] = newProps[key]
                }
            }
              // count等于零则没有变化
            if (count === 0) {
                return null
            }
             return propsPatches
        }

现在我们就需要将补丁包与真实的DOM相结合。

function patch(node, patches) {
            var walker = {
                //这里的index可以帮我们匹配到我们对应的补丁包
                index: 0
            }
            dfsWalk(node, walker, patches)
        }

        function dfsWalk(node, walker, patches) {
            var currentPatches = patches[walker.index] // 从patches拿出当前节点的差异

            var len = node.childNodes ?
                node.childNodes.length :
                0
            for (var i = 0; i < len; i++) { // 用递归深度遍历子节点
                var child = node.childNodes[i]
                walker.index++
                dfsWalk(child, walker, patches)
            }

            if (currentPatches) {
                applyPatches(node, currentPatches) // 对当前节点进行DOM操作
            }
        }

applyPatches方法,根据不同类型的差异对当前节点进行 DOM 操作:

 function applyPatches(node, currentPatches) {
            currentPatches.forEach(function(currentPatch) {
                switch (currentPatch.type) {
                    case REPLACE:
                        node.parentNode.replaceChild(currentPatch.node.render(), node)
                        break
                    case REORDER:
                        reorderChildren(node, currentPatch.moves)
                        break
                    case PROPS:
                        setProps(node, currentPatch.props)
                        break
                    case TEXT:
                        node.textContent = currentPatch.content
                        break
                    default:
                        throw new Error('Unknown patch type ' + currentPatch.type)
                }
            })
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值