开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 11 天,点击查看活动详情
纯运行时
const obj = {
tag: 'div'
children:[{tag: 'span', children: 'hello world'}]
}
Render(obj, document.body)
function Render(obj, root) {
// 创建tag标签
const element = document.crenteElement(obj.tag)
// 如果children是string类型的那么就创建textNode节点。
if (typeof obj.children === 'string'){
const text = document.crenteTextNode(obj.children)
el.appendChild(text)
} else if(Array.isArray(obj.children)) {
// 循环遍历
obj.children.forEach(item => Render(child, elment))
}
root.appendChild(element)
}
此段代码不需要编译,直接在浏览器运行就能得到我们想要的结果。
编译时 + 运行时
需求:我们需要jsx那样写样式。
那么我们就必须
- 先写jsx语法
- jsx编译成为浏览器识别的
- 最后调用render渲染
//jsx代码
<div>
<span>hello world</span>
</div>
// 使用编译器命令将jsx编译成字典形式的代码
const obj = {
tag: 'div'
children:[{tag: 'span', children: 'hello world'}]
}
再调用
Render(obj, document.body)
vue和react就是编译时 + 运行时的。在编译提取代码信息,render阶段做进一步的优化。 纯编译时 性能可能会更好,但是损失了灵活性, 用户提供的内容必须编译后才能用。 纯运行时的的代码因为没有编译过程,我们无法分析用户提供的内容。
纯编译时
一次性将代码编译成为浏览器运行的内容。不支持任何运行时内容,用户代码通过编译器编译后才能运行。
//jsx代码
<div>
<span>hello world</span>
</div>
用编译器直接编译成为了
const div = document.crentElement('div')
const span = document.crentElement('span')
span.innerText = 'hello world‘
div.appendChild(span)
document.body.appendChild(div)
总结: 设计框架的时候,我们既可以是纯编译时,也可以是纯运行时,还可以是编译时+运行时组合。对于如何选择,需根据我们需求以及各自特性综合考虑 编译时 + 运行时的:可以在编译提取代码信息,render阶段做进一步的优化。 纯运行时:代码因为没有编译过程,我们无法分析用户提供的内容。 纯编译时: 性能可能会更好,但是损失了灵活性, 用户提供的内容必须编译后才能用。
开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 11 天,点击查看活动详情