一、DOM 节点基础概念
1. DOM 是什么?
DOM(Document Object Model) 是浏览器将 HTML/XML 文档解析成的一个树形结构模型,使 JavaScript 能够操作网页的内容、结构和样式。
// HTML文档
<html>
<body>
<div id="app">
<h1>Hello World</h1>
<p>DOM示例</p>
</div>
</body>
</html>
// 对应的DOM树结构
- Document
- html (Element)
- body (Element)
- div#app (Element, id="app")
- h1 (Element)
- "Hello World" (Text)
- p (Element)
- "DOM示例" (Text)
2. DOM 节点类型(核心考点)
| 节点类型 | Node Type 常量 | 值 | 示例 |
|---|---|---|---|
| 元素节点 | Node.ELEMENT_NODE | 1 | <div>, <p>, <span> |
| 文本节点 | Node.TEXT_NODE | 3 | "Hello", "World" |
| 属性节点 | Node.ATTRIBUTE_NODE | 2 | class="container" |
| 注释节点 | Node.COMMENT_NODE | 8 | <!-- 注释 --> |
| 文档节点 | Node.DOCUMENT_NODE | 9 | document |
| 文档类型节点 | Node.DOCUMENT_TYPE_NODE | 10 | <!DOCTYPE html> |
| 文档片段节点 | Node.DOCUMENT_FRAGMENT_NODE | 11 | document.createDocumentFragment() |
// 检查节点类型
const element = document.getElementById('app');
console.log(element.nodeType); // 1 (ELEMENT_NODE)
console.log(element.nodeType === Node.ELEMENT_NODE); // true
const text = element.firstChild;
console.log(text.nodeType); // 3 (TEXT_NODE)
// 获取所有节点类型
for (let i = 0; i <= 12; i++) {
const nodeName = Object.keys(Node).find(key => Node[key] === i);
console.log(`${i}: ${nodeName || 'Unknown'}`);
}
3. DOM 节点属性和方法(面试重点)
// 节点属性
const node = document.querySelector('div');
console.log(node.nodeName); // "DIV" - 节点名称
console.log(node.nodeType); // 1 - 节点类型
console.log(node.nodeValue); // null(元素节点)或 文本内容(文本节点)
// 节点关系属性
console.log(node.parentNode); // 父节点
console.log(node.childNodes); // 子节点列表(NodeList)
console.log(node.firstChild); // 第一个子节点
console.log(node.lastChild); // 最后一个子节点
console.log(node.previousSibling); // 前一个兄弟节点
console.log(node.nextSibling); // 后一个兄弟节点
// 元素特有属性(仅适用于元素节点)
console.log(node.tagName); // "DIV"
console.log(node.id); // "app"
console.log(node.className); // "container"
console.log(node.classList); // DOMTokenList ["container"]
console.log(node.innerHTML); // 内部HTML字符串
console.log(node.outerHTML); // 包含自身的HTML字符串
console.log(node.textContent); // 所有文本内容(包括隐藏元素)
console.log(node.innerText); // 可见文本内容
4. DOM 操作 API(必考)
// 创建节点
const newDiv = document.createElement('div');
const newText = document.createTextNode('Hello World');
const comment = document.createComment('This is a comment');
const fragment = document.createDocumentFragment();
// 添加节点
parent.appendChild(newDiv); // 添加到末尾
parent.insertBefore(newDiv, referenceNode); // 插入到指定节点前
parent.replaceChild(newDiv, oldNode); // 替换节点
// 移除节点
parent.removeChild(childNode);
childNode.remove(); // ES5+
// 克隆节点
const clone = node.cloneNode(true); // 深度克隆(包含子节点)
const shallowClone = node.cloneNode(false); // 浅克隆(不包含子节点)
// 查询节点
document.getElementById('id'); // 通过ID
document.getElementsByClassName('class'); // 通过class
document.getElementsByTagName('div'); // 通过标签名
document.querySelector('#id .class'); // CSS选择器(第一个)
document.querySelectorAll('.item'); // CSS选择器(全部)
二、虚拟 DOM 概念与原理
1. 虚拟 DOM 是什么?
虚拟 DOM 是一个用 JavaScript 对象模拟真实 DOM 的轻量级内存表示。
// 真实DOM节点
<div id="app" class="container">
<h1>Hello</h1>
<p>World</p>
</div>
// 对应的虚拟DOM对象(React示例)
const virtualNode = {
type: 'div',
props: {
id: 'app',
className: 'container',
children: [
{
type: 'h1',
props: {
children: 'Hello'
}
},
{
type: 'p',
props: {
children: 'World'
}
}
]
}
};
// Vue的虚拟DOM结构
const vnode = {
tag: 'div',
data: {
attrs: { id: 'app' },
class: 'container'
},
children: [
{ tag: 'h1', children: 'Hello' },
{ tag: 'p', children: 'World' }
]
};
2. 虚拟 DOM 的工作流程
1. 初始化阶段
真实 DOM → 虚拟 DOM 快照
2. 状态变化时
a. 创建新的虚拟 DOM 树
b. 与旧的虚拟 DOM 进行 diff 比较
c. 计算最小变更集(patch)
d. 批量更新真实 DOM
3. 渲染阶段
应用变更到真实 DOM
// 简化版虚拟DOM实现
class VNode {
constructor(tag, props, children) {
this.tag = tag; // 标签名
this.props = props; // 属性对象
this.children = children; // 子节点数组
this.key = props?.key; // 优化key
}
}
// Diff算法简化示例
function diff(oldVNode, newVNode) {
const patches = [];
// 1. 节点类型不同,直接替换
if (oldVNode.tag !== newVNode.tag) {
patches.push({ type: 'REPLACE', node: newVNode });
return patches;
}
// 2. 属性比较
const propPatches = diffProps(oldVNode.props, newVNode.props);
if (propPatches.length > 0) {
patches.push({ type: 'PROPS', props: propPatches });
}
// 3. 子节点比较
const childPatches = diffChildren(oldVNode.children, newVNode.children);
if (childPatches.length > 0) {
patches.push({ type: 'CHILDREN', patches: childPatches });
}
return patches;
}
三、虚拟 DOM vs 真实 DOM:核心区别
| 对比维度 | 真实 DOM | 虚拟 DOM |
|---|---|---|
| 本质 | 浏览器原生对象,重量级 | JavaScript 对象,轻量级 |
| 创建成本 | 高(涉及浏览器渲染流程) | 低(纯 JS 对象) |
| 更新性能 | 直接操作成本高,回流重绘 | 批量更新,减少 DOM 操作 |
| 内存占用 | 占用大量内存 | 占用较少内存 |
| 更新机制 | 立即同步更新 | 异步批量更新 |
| 跨平台 | 依赖浏览器环境 | 可跨平台(React Native, SSR) |
| 开发体验 | 手动管理更新,易出错 | 声明式,自动处理更新 |
1. 性能差异对比
// 性能对比示例:更新1000个列表项
// 方式1:直接操作真实DOM(性能差)
function updateRealDOM() {
const start = performance.now();
const list = document.getElementById('list');
list.innerHTML = ''; // 清空(触发重排)
for (let i = 0; i < 1000; i++) {
const item = document.createElement('li');
item.textContent = `Item ${i}`;
list.appendChild(item); // 每次append都可能导致重排
}
const end = performance.now();
console.log(`Real DOM: ${end - start}ms`);
}
// 方式2:使用虚拟DOM(性能好)
function updateVirtualDOM() {
const start = performance.now();
// 1. 生成新的虚拟DOM
const newVNode = {
tag: 'ul',
children: Array.from({ length: 1000 }, (_, i) => ({
tag: 'li',
children: `Item ${i}`
}))
};
// 2. Diff比较(内存中进行,很快)
const patches = diff(oldVNode, newVNode);
// 3. 批量更新真实DOM
batchUpdate(patches);
const end = performance.now();
console.log(`Virtual DOM: ${end - start}ms`);
}
// 测试结果:虚拟DOM通常快3-10倍
updateRealDOM(); // 大约 50-100ms
updateVirtualDOM(); // 大约 10-30ms
2. 更新机制对比
// 真实DOM更新:每次修改都触发重排重绘
const div = document.getElementById('app');
// 多次操作,多次重排
div.style.color = 'red'; // 触发重绘
div.style.width = '100px'; // 触发重排+重绘
div.style.height = '100px'; // 触发重排+重绘
div.textContent = 'New Text'; // 触发重排+重绘
// 总计:3次重排,4次重绘
// 虚拟DOM更新:批量处理
const updateQueue = [];
let isBatching = false;
function scheduleUpdate(update) {
updateQueue.push(update);
if (!isBatching) {
isBatching = true;
// 下一个事件循环批量处理
Promise.resolve().then(() => {
const patches = [];
// 收集所有变更
while (updateQueue.length) {
patches.push(...updateQueue.shift());
}
// 一次性更新真实DOM
applyPatches(patches);
isBatching = false;
});
}
}
// 多次修改只触发一次更新
scheduleUpdate([{ type: 'COLOR', color: 'red' }]);
scheduleUpdate([{ type: 'WIDTH', width: '100px' }]);
scheduleUpdate([{ type: 'HEIGHT', height: '100px' }]);
scheduleUpdate([{ type: 'TEXT', text: 'New Text' }]);
// 总计:1次重排,1次重绘
3. Diff 算法原理(面试高频考点)
// React的Diff算法策略
class ReactDiff {
// 策略1:同级比较,不跨级移动
diffLevel(oldVNode, newVNode, index = 0, patches) {
if (!oldVNode) {
// 新增节点
patches.push({ type: 'CREATE', vnode: newVNode });
} else if (!newVNode) {
// 删除节点
patches.push({ type: 'REMOVE', index });
} else if (isSameVNode(oldVNode, newVNode)) {
// 相同节点,比较属性和子节点
this.diffProps(oldVNode, newVNode, patches);
this.diffChildren(oldVNode, newVNode, patches);
} else {
// 节点不同,直接替换
patches.push({ type: 'REPLACE', vnode: newVNode });
}
}
// 策略2:使用key优化列表对比
diffChildrenWithKey(oldChildren, newChildren, patches) {
const oldMap = new Map();
oldChildren.forEach((child, i) => {
if (child.key) oldMap.set(child.key, { vnode: child, index: i });
});
const newMap = new Map();
newChildren.forEach((child, i) => {
if (child.key) newMap.set(child.key, { vnode: child, index: i });
});
// 识别移动、新增、删除的节点
for (const [key, oldInfo] of oldMap) {
if (!newMap.has(key)) {
// 删除
patches.push({ type: 'REMOVE', index: oldInfo.index });
} else {
const newInfo = newMap.get(key);
if (oldInfo.index !== newInfo.index) {
// 移动
patches.push({ type: 'MOVE', from: oldInfo.index, to: newInfo.index });
}
// 继续比较属性
this.diffProps(oldInfo.vnode, newInfo.vnode, patches);
}
}
for (const [key, newInfo] of newMap) {
if (!oldMap.has(key)) {
// 新增
patches.push({ type: 'CREATE', vnode: newInfo.vnode, index: newInfo.index });
}
}
}
// 策略3:组件类型相同则更新,不同则替换
diffComponent(oldComp, newComp, patches) {
if (oldComp.constructor === newComp.constructor) {
// 相同组件,更新props
if (shouldUpdate(oldComp.props, newComp.props)) {
patches.push({ type: 'UPDATE_COMPONENT', component: newComp });
}
} else {
// 不同组件,完全替换
patches.push({ type: 'REPLACE_COMPONENT', component: newComp });
}
}
}
四、各框架的虚拟 DOM 实现差异
1. React 的虚拟 DOM
// React元素(虚拟DOM的基础单元)
const element = {
$$typeof: Symbol.for('react.element'),
type: 'div', // 或函数组件/类组件
key: null,
ref: null,
props: {
children: 'Hello',
className: 'container',
onClick: () => {}
},
_owner: null,
_store: {}
};
// React Fiber架构(优化版虚拟DOM)
class FiberNode {
constructor(tag, pendingProps, key) {
this.tag = tag; // 组件类型
this.key = key; // 优化标识
this.elementType = null; // 原始类型
this.type = null; // 解析后类型
this.stateNode = null; // 对应的真实DOM
this.return = null; // 父节点
this.child = null; // 第一个子节点
this.sibling = null; // 兄弟节点
this.index = 0; // 在兄弟中的索引
this.ref = null; // ref引用
this.pendingProps = pendingProps; // 新props
this.memoizedProps = null; // 已生效的props
this.memoizedState = null; // 已生效的state
this.updateQueue = null; // 更新队列
this.effectTag = NoEffect; // 副作用标签
this.alternate = null; // 连接新旧fiber
}
}
2. Vue 的虚拟 DOM
// Vue 3的虚拟节点
const vnode = {
__v_isVNode: true,
__v_skip: true,
type: 'div', // 组件或标签名
props: {
class: 'container',
style: { color: 'red' },
onClick: handler
},
key: null,
ref: null,
scopeId: null,
children: [
{ type: 'span', children: 'Hello' }
],
component: null,
suspense: null,
dirs: null,
transition: null,
el: null, // 对应的真实DOM
anchor: null,
target: null,
targetAnchor: null,
staticCount: 0,
shapeFlag: 16, // 节点类型标记
patchFlag: 8, // 优化标记
dynamicProps: null,
dynamicChildren: null,
appContext: null
};
// Vue的编译时优化
const template = `<div>
<span>{{ message }}</span>
<button @click="handleClick">Click</button>
</div>`;
// 编译后生成优化过的渲染函数
function render(_ctx, _cache) {
return (_openBlock(), _createBlock("div", null, [
_createVNode("span", null, _toDisplayString(_ctx.message), 1 /* TEXT */),
_createVNode("button", { onClick: _ctx.handleClick }, "Click", 8 /* PROPS */, ["onClick"])
]))
}
3. 框架间虚拟DOM对比
| 框架 | Diff策略 | 优化特点 | 更新粒度 |
|---|---|---|---|
| React | 深度优先,双指针 | Fiber可中断渲染 | 组件级 |
| Vue 2 | 双端比较 | 静态节点提升 | 组件级 |
| Vue 3 | 快速Diff + 预处理 | PatchFlag静态标记 | 元素级 |
| Inferno | 启发式Diff | 极致性能优化 | 元素级 |
| Preact | 简单Diff | 轻量级实现 | 组件级 |
五、虚拟 DOM 的优缺点(面试必问)
优点:
-
性能优化:批量更新,减少 DOM 操作次数
-
跨平台:一套代码可渲染到 Web、Native、Canvas 等
-
声明式编程:关注状态而非 DOM 操作
-
抽象层:屏蔽浏览器兼容性问题
-
SSR 友好:服务端可生成虚拟 DOM 字符串
缺点:
-
内存开销:需要维护额外的虚拟 DOM 树
-
初始渲染慢:需要先创建虚拟 DOM 再渲染
-
复杂场景优化难:极端性能需求需要手动优化
-
学习成本:需要理解新的抽象概念
-
不适合小项目:简单项目可能增加复杂度
何时不适合使用虚拟 DOM:
// 场景1:频繁操作的小规模DOM
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 游戏渲染循环:直接操作性能更好
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(player.x, player.y, 50, 50); // 直接绘制,无需虚拟DOM
requestAnimationFrame(gameLoop);
}
// 场景2:高实时性要求的应用
// 如股票行情、实时监控,需要直接操作DOM确保最低延迟
function updateStockPrice(price) {
// 直接更新,避免虚拟DOM的diff开销
document.getElementById('price').textContent = price;
}
// 场景3:复杂的动画序列
// 直接使用Web Animation API性能更好
element.animate([
{ transform: 'translateX(0px)' },
{ transform: 'translateX(100px)' }
], {
duration: 1000,
easing: 'ease-in-out'
});
六、面试考点总结
高频面试问题:
Q1:虚拟DOM一定比真实DOM快吗?
不一定。虚拟DOM在复杂、频繁更新的场景下有优势,但在简单、一次性操作中可能更慢,因为:
1. 需要创建和维护虚拟DOM树
2. Diff算法有计算开销
3. 初始渲染需要额外步骤
适用场景:
- 复杂UI,频繁更新 ✓
- 简单静态页面 ✗
- 需要跨平台渲染 ✓
- 极致性能要求的游戏 ✗
Q2:React的Fiber架构解决了什么?
1. 可中断渲染:将渲染任务拆分为小单元,可暂停/恢复
2. 优先级调度:高优先级任务可打断低优先级
3. 更好的错误处理:组件边界错误隔离
4. 并发模式:支持并发更新
Q3:Vue3的静态提升是什么?
// Vue3编译优化示例
// 编译前
const template = `<div>
<h1>Static Title</h1> <!-- 静态节点 -->
<p>{{ dynamic }}</p> <!-- 动态节点 -->
</div>`;
// 编译后
const hoisted = createVNode("h1", null, "Static Title"); // 静态节点被提升
function render(ctx) {
return createVNode("div", null, [
hoisted, // 复用静态节点
createVNode("p", null, ctx.dynamic, 1) // 仅动态节点参与Diff
]);
}
Q4:key的作用和原理?
// 没有key:按索引对比,可能错误复用
const oldList = ['A', 'B', 'C'];
const newList = ['D', 'A', 'B', 'C']; // 插入D到开头
// 有key:正确识别节点身份
const oldList = [
{ id: 1, name: 'A' },
{ id: 2, name: 'B' },
{ id: 3, name: 'C' }
];
const newList = [
{ id: 4, name: 'D' }, // 新增
{ id: 1, name: 'A' }, // 复用
{ id: 2, name: 'B' }, // 复用
{ id: 3, name: 'C' } // 复用
];
性能优化建议:
// 1. 合理使用key
// 错误:使用索引作为key
items.map((item, index) => <li key={index}>{item}</li>);
// 正确:使用唯一标识作为key
items.map(item => <li key={item.id}>{item.name}</li>);
// 2. 避免不必要的渲染
// React: 使用React.memo, useMemo, useCallback
const MemoComponent = React.memo(MyComponent);
// Vue: 使用v-once, computed, watch
<div v-once>{{ staticContent }}</div>
// 3. 合理拆分组件
// 将频繁更新的部分拆分出来
function App() {
const [count, setCount] = useState(0);
return (
<div>
{/* 频繁更新部分 */}
<Counter count={count} />
{/* 静态部分 */}
<StaticContent />
</div>
);
}
// 4. 使用虚拟列表优化长列表
import { FixedSizeList } from 'react-window';
function VirtualList() {
return (
<FixedSizeList
height={400}
width={300}
itemCount={1000}
itemSize={50}
>
{({ index, style }) => (
<div style={style}>Row {index}</div>
)}
</FixedSizeList>
);
}
掌握这些核心概念和差异,能够在面试中清晰阐述虚拟DOM的价值、原理和适用场景,体现对前端渲染机制的深入理解。
269



被折叠的 条评论
为什么被折叠?



