众所周知,操做 DOM 是很耗费性能的一件事情,既然如此,咱们能够考虑经过 JS 对象来模拟 DOM 对象,毕竟操做 JS 对象比操做 DOM 省时的多。node
举个例子git
// 假设这里模拟一个 ul,其中包含了 5 个 li
[1, 2, 3, 4, 5]
// 这里替换上面的 li
[1, 2, 5, 4]
复制代码
从上述例子中,咱们一眼就能够看出先前的 ul 中的第三个 li 被移除了,四五替换了位置。github
若是以上操做对应到 DOM 中,那么就是如下代码算法
// 删除第三个 li
ul.childNodes[2].remove()
// 将第四个 li 和第五个交换位置
let fromNode = ul.childNodes[4]
let toNode = node.childNodes[3]
let cloneFromNode = fromNode.cloneNode(true)
let cloenToNode = toNode.cloneNode(true)
ul.replaceChild(cloneFromNode, toNode)
ul.replaceChild(cloenToNode, fromNode)
复制代码
固然在实际操做中,咱们还须要给每一个节点一个标识,做为判断是同一个节点的依据。因此这也是 Vue 和 React 中官方推荐列表里的节点使用惟一的 key
来保证性能。数组
那么既然 DOM 对象能够经过 JS 对象来模拟,反之也能够经过 JS 对象来渲染出对应的 DOMapp
如下是一个 JS 对象模拟 DOM 对象的简单实现dom
export default class Element {
/** * @param {String} tag 'div' * @param {Object} props { class: 'item' } * @param {Array} children [ Element1, 'text'] * @param {String} key option */
constructor(tag, props, children, key) {
this.tag = tag
this.props = props
if (Array.isArray(children)) {
this.children = children
} else if (isString(children)) {
this.key = children
this.children = null
}
if (key) this.key = key
}
// 渲染
render() {
let root = this._createElement(
this.tag,
this.props,
this.children,
this.key
)
document.body.appendChild(root)
return root
}
create() {
return this._createElement(this.tag, this.props, this.children, this.key)
}
// 建立节点
_createElement(tag, props, child, key) {
// 经过 tag 建立节点
let el = document.createElement(tag)
// 设置节点属性
for (const key in props) {
if (props.hasOwnProperty(key)) {
const value = props[key]
el.setAttribute(key, value)
}
}
if (key) {
el.setAttribute('key', key)
}
// 递归添加子节点
if (child) {
child.forEach(element => {
let child
if (element instanceof Element) {
child = this._createElement(
element.tag,
element.props,
element.children,
element.key
)
} else {
child = document.createTextNode(element)
}
el.appendChild(child)
})
}
return el
}
}
复制代码
既然咱们已经经过 JS 来模拟实现了 DOM,那么接下来的难点就在于如何判断旧的对象和新的对象之间的差别。函数
DOM 是多叉树的结构,若是须要完整的对比两颗树的差别,那么须要的时间复杂度会是 O(n ^ 3),这个复杂度确定是不能接受的。因而 React 团队优化了算法,实现了 O(n) 的复杂度来对比差别。性能
实现 O(n) 复杂度的关键就是只对比同层的节点,而不是跨层对比,这也是考虑到在实际业务中不多会去跨层的移动 DOM 元素。优化
因此判断差别的算法就分为了两步
首先咱们来实现树的递归算法,在实现该算法前,先来考虑下两个节点对比会有几种状况
tagName
或者 key
和旧的不一样,这种状况表明须要替换旧的节点,而且也再也不须要遍历新旧节点的子元素了,由于整个旧节点都被删掉了tagName
和 key
(可能都没有)和旧的相同,开始遍历子树import { StateEnums, isString, move } from './util'
import Element from './element'
export default function diff(oldDomTree, newDomTree) {
// 用于记录差别
let pathchs = {}
// 一开始的索引为 0
dfs(oldDomTree, newDomTree, 0, pathchs)
return pathchs
}
function dfs(oldNode, newNode, index, patches) {
// 用于保存子树的更改
let curPatches = []
// 须要判断三种状况
// 1.没有新的节点,那么什么都不用作
// 2.新的节点的 tagName 和 `key` 和旧的不一样,就替换
// 3.新的节点的 tagName 和 key(可能都没有) 和旧的相同,开始遍历子树
if (!newNode) {
} else if (newNode.tag === oldNode.tag && newNode.key === oldNode.key) {
// 判断属性是否变动
let props = diffProps(oldNode.props, newNode.props)
if (props.length) curPatches.push({ type: StateEnums.ChangeProps, props })
// 遍历子树
diffChildren(oldNode.children, newNode.children, index, patches)
} else {
// 节点不一样,须要替换
curPatches.push({ type: StateEnums.Replace, node: newNode })
}
if (curPatches.length) {
if (patches[index]) {
patches[index] = patches[index].concat(curPatches)
} else {
patches[index] = curPatches
}
}
}
复制代码
判断属性的更改也分三个步骤
function diffProps(oldProps, newProps) {
// 判断 Props 分如下三步骤
// 先遍历 oldProps 查看是否存在删除的属性
// 而后遍历 newProps 查看是否有属性值被修改
// 最后查看是否有属性新增
let change = []
for (const key in oldProps) {
if (oldProps.hasOwnProperty(key) && !newProps[key]) {
change.push({
prop: key
})
}
}
for (const key in newProps) {
if (newProps.hasOwnProperty(key)) {
const prop = newProps[key]
if (oldProps[key] && oldProps[key] !== newProps[key]) {
change.push({
prop: key,
value: newProps[key]
})
} else if (!oldProps[key]) {
change.push({
prop: key,
value: newProps[key]
})
}
}
}
return change
}
复制代码
这个算法是整个 Virtual Dom 中最核心的算法,且让我一一为你道来。 这里的主要步骤其实和判断属性差别是相似的,也是分为三步
PS:该算法只对有 key
的节点作处理
function listDiff(oldList, newList, index, patches) {
// 为了遍历方便,先取出两个 list 的全部 keys
let oldKeys = getKeys(oldList)
let newKeys = getKeys(newList)
let changes = []
// 用于保存变动后的节点数据
// 使用该数组保存有如下好处
// 1.能够正确得到被删除节点索引
// 2.交换节点位置只须要操做一遍 DOM
// 3.用于 `diffChildren` 函数中的判断,只须要遍历
// 两个树中都存在的节点,而对于新增或者删除的节点来讲,彻底不必
// 再去判断一遍
let list = []
oldList &&
oldList.forEach(item => {
let key = item.key
if (isString(item)) {
key = item
}
// 寻找新的 children 中是否含有当前节点
// 没有的话须要删除
let index = newKeys.indexOf(key)
if (index === -1) {
list.push(null)
} else list.push(key)
})
// 遍历变动后的数组
let length = list.length
// 由于删除数组元素是会更改索引的
// 全部从后往前删能够保证索引不变
for (let i = length - 1; i >= 0; i--) {
// 判断当前元素是否为空,为空表示须要删除
if (!list[i]) {
list.splice(i, 1)
changes.push({
type: StateEnums.Remove,
index: i
})
}
}
// 遍历新的 list,判断是否有节点新增或移动
// 同时也对 `list` 作节点新增和移动节点的操做
newList &&
newList.forEach((item, i) => {
let key = item.key
if (isString(item)) {
key = item
}
// 寻找旧的 children 中是否含有当前节点
let index = list.indexOf(key)
// 没找到表明新节点,须要插入
if (index === -1 || key == null) {
changes.push({
type: StateEnums.Insert,
node: item,
index: i
})
list.splice(i, 0, key)
} else {
// 找到了,须要判断是否须要移动
if (index !== i) {
changes.push({
type: StateEnums.Move,
from: index,
to: i
})
move(list, index, i)
}
}
})
return { changes, list }
}
function getKeys(list) {
let keys = []
let text
list &&
list.forEach(item => {
let key
if (isString(item)) {
key = [item]
} else if (item instanceof Element) {
key = item.key
}
keys.push(key)
})
return keys
}
复制代码
对于这个函数来讲,主要功能就两个
整体来讲,该函数实现的功能很简单
function diffChildren(oldChild, newChild, index, patches) {
let { changes, list } = listDiff(oldChild, newChild, index, patches)
if (changes.length) {
if (patches[index]) {
patches[index] = patches[index].concat(changes)
} else {
patches[index] = changes
}
}
// 记录上一个遍历过的节点
let last = null
oldChild &&
oldChild.forEach((item, i) => {
let child = item && item.children
if (child) {
index =
last && last.children ? index + last.children.length + 1 : index + 1
let keyIndex = list.indexOf(item.key)
let node = newChild[keyIndex]
// 只遍历新旧中都存在的节点,其余新增或者删除的不必遍历
if (node) {
dfs(item, node, index, patches)
}
} else index += 1
last = item
})
}
复制代码
经过以前的算法,咱们已经能够得出两个树的差别了。既然知道了差别,就须要局部去更新 DOM 了,下面就让咱们来看看 Virtual Dom 算法的最后一步骤
这个函数主要两个功能
总体来讲这部分代码仍是很好理解的
let index = 0
export default function patch(node, patchs) {
let changes = patchs[index]
let childNodes = node && node.childNodes
// 这里的深度遍历和 diff 中是同样的
if (!childNodes) index += 1
if (changes && changes.length && patchs[index]) {
changeDom(node, changes)
}
let last = null
if (childNodes && childNodes.length) {
childNodes.forEach((item, i) => {
index =
last && last.children ? index + last.children.length + 1 : index + 1
patch(item, patchs)
last = item
})
}
}
function changeDom(node, changes, noChild) {
changes &&
changes.forEach(change => {
let { type } = change
switch (type) {
case StateEnums.ChangeProps:
let { props } = change
props.forEach(item => {
if (item.value) {
node.setAttribute(item.prop, item.value)
} else {
node.removeAttribute(item.prop)
}
})
break
case StateEnums.Remove:
node.childNodes[change.index].remove()
break
case StateEnums.Insert:
let dom
if (isString(change.node)) {
dom = document.createTextNode(change.node)
} else if (change.node instanceof Element) {
dom = change.node.create()
}
node.insertBefore(dom, node.childNodes[change.index])
break
case StateEnums.Replace:
node.parentNode.replaceChild(change.node.create(), node)
break
case StateEnums.Move:
let fromNode = node.childNodes[change.from]
let toNode = node.childNodes[change.to]
let cloneFromNode = fromNode.cloneNode(true)
let cloenToNode = toNode.cloneNode(true)
node.replaceChild(cloneFromNode, toNode)
node.replaceChild(cloenToNode, fromNode)
break
default:
break
}
})
}
复制代码
Virtual Dom 算法的实现也就是如下三步
let test4 = new Element('div', { class: 'my-div' }, ['test4'])
let test5 = new Element('ul', { class: 'my-div' }, ['test5'])
let test1 = new Element('div', { class: 'my-div' }, [test4])
let test2 = new Element('div', { id: '11' }, [test5, test4])
let root = test1.render()
let pathchs = diff(test1, test2)
console.log(pathchs)
setTimeout(() => {
console.log('开始更新')
patch(root, pathchs)
console.log('结束更新')
}, 1000)
复制代码
固然目前的实现还略显粗糙,可是对于理解 Virtual Dom 算法来讲已是彻底足够的了。
文章中的代码你能够在 这里 阅读。本系列更新的文章都会更新在这个仓库中,有兴趣的能够关注下。
下篇文章的内容将会是状态管理,敬请期待。
最后附上个人公众号