前言:
前几周在研究Vue的源码,感觉设计得还是蛮精巧的。这里主要谈谈其异步更新的机制,及实现nextTick的几种方式,接着会扩展一些浏览器的event-loop的实现机制。
目录:
nextTick 与异步渲染UI
vue中,data的改变是同步的,reactive的,但ui的渲染是异步,正如nextTick 一样,都是在下一个tick去执行。
这篇文章讲得比较细,但可能用的是老版本的vue了,只涉及到了MutationObserver 和 setTimeout。
Vue nextTick 源码解读
这里的vue版本是2.5.17-beta.0。大致有以下几个要点:
- flushCallbacks 用来清空回调队列和依次执行回调。
- 定义了两个timerFunc, microTimerFunc用于执行微任务microtasks,macroTimerFunc 用于执行任务tasks。
- 放弃了MutationObserver,用setImmediate -> setImmdiate的polyfill MessageChannel -> setTimeout(fn, 0) 来构造 macroTimerFunc
- 用 Promise.resolve().then(flushCallbacks) 来构造microTimerFunc, 若没有原生支持的Promise, 则microTimerFunc 退化为 macroTimerFunc
- 默认使用 microtask 但暴露了强制使用task 的方法,如v-on绑定的事件handler
- nextTick中接受一个cb 函数,和一个上下文对象ctx,主要做了两件事
- 把cb压入回调队列
- 如果没有正在执行任务(任务队列是空的),则使用 macroTimerFunc()/ microTimerFunc() 执行flushCallbacks 清空队列。
附源代码:core/util/next-tick.js
/* @flow */
/* globals MessageChannel */
import { noop } from 'shared/util'
import { handleError } from './error'
import { isIOS, isNative } from './env'
const callbacks = []
let pending = false
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
// Here we have async deferring wrappers using both microtasks and (macro) tasks.
// In < 2.4 we used microtasks everywhere, but there are some scenarios where
// microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690) or even between bubbling of the same
// event (#6566). However, using (macro) tasks everywhere also has subtle problems
// when state is changed right before repaint (e.g. #6813, out-in transitions).
// Here we use microtask by default, but expose a way to force (macro) task when
// needed (e.g. in event handlers attached by v-on).
let microTimerFunc
let macroTimerFunc
let useMacroTask = false
// Determine (macro) task defer implementation.
// Technically setImmediate should be the ideal choice, but it's only available
// in IE. The only polyfill that consistently queues the callback after all DOM
// events triggered in the same loop is by using MessageChannel.
/* istanbul ignore if */
if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
macroTimerFunc = () => {
setImmediate(flushCallbacks)
}
} else if (typeof MessageChannel !== 'undefined' && (
isNative(MessageChannel) ||
// PhantomJS
MessageChannel.toString() === '[object MessageChannelConstructor]'
)) {
const channel = new MessageChannel()
const port = channel.port2
channel.port1.onmessage = flushCallbacks
macroTimerFunc = () => {
port.postMessage(1)
}
} else {
/* istanbul ignore next */
macroTimerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
// Determine microtask defer implementation.
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve()
microTimerFunc = () => {
p.then(flushCallbacks)
// in problematic UIWebViews, Promise.then doesn't completely break, but
// it can get stuck in a weird state where callbacks are pushed into the
// microtask queue but the queue isn't being flushed, until the browser
// needs to do some other work, e.g. handle a timer. Therefore we can
// "force" the microtask queue to be flushed by adding an empty timer.
if (isIOS) setTimeout(noop)
}
} else {
// fallback to macro
microTimerFunc = macroTimerFunc
}
/**
* Wrap a function so that if any code inside triggers state change,
* the changes are queued using a (macro) task instead of a microtask.
*/
export function withMacroTask (fn: Function): Function {
return fn._withTask || (fn._withTask = function () {
useMacroTask = true
const res = fn.apply(null, arguments)
useMacroTask = false
return res
})
}
export function nextTick (cb?: Function, ctx?: Object) {
let _resolve
callbacks.push(() => {
if (cb) {
try {
cb.call(ctx)
} catch (e) {
handleError(e, ctx, 'nextTick')
}
} else if (_resolve) {
_resolve(ctx)
}
})
if (!pending) {
pending = true
if (useMacroTask) {
macroTimerFunc()
} else {
microTimerFunc()
}
}
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}
浏览器的event-loop
主要参见这篇文章:Tasks, microtasks, queues and schedules
猜猜这段代码的输出结果?
console.log('script start');
setTimeout(function() {
console.log('setTimeout');
}, 0);
Promise.resolve().then(function() {
console.log('promise1');
}).then(function() {
console.log('promise2');
});
console.log('script end');
一个正确实现了 Ecmascript 的浏览器的输出结果是:
script start, script end, promise1, promise2, setTimeout。
这与浏览器的event loop实现机制有关系。
浏览器中,每个线程都维护着自己的event loop 。所有同一来源的窗口都共享一个event loop 从而可以同步地通信。
一个事件循环有多个任务来源,在循环内部会确保任务的执行顺序。但浏览器要在每个循环执行完后从任务来源中挑选一个来执行任务。浏览器优先执行性能敏感的任务,如I/O输入。
任务(tasks)被作了日程安排(scheduled)。在任务之间,浏览器也许会 更新渲染。
setTimout 会等待一会儿,再为它的回调安排一个新任务。
微任务(microtasks)会把事务安排在当前执行的代码后立即做。如执行一个异步,但不需要重启一个全新的任务。微任务队列会放在没有别的js在执行后做,即每个task的末位。新加入的microtask会被排在当前的微任务队列中。微任务包括mutation observer 的回调和promises。微任务总是在下一个任务执行前完成。
某些浏览器的版本,如safari 和 firefox 40, 微软的Edge 把promise当做任务来处理了。这会造成性能损失。
尽管我们正处于任务之中,只要JS的堆栈空了,微任务就会被放到回调后处理。
微任务在事件Listener的回调之间运行。但不会打扰正在执行的js。
微任务队列和schedules中还给了一个浏览器中点击事件的例子,值得一提的是,手动点击和用.click()来模拟的结果是不一样的。因为.click()会让同步分发事件。
总结:
- 任务按次序执行,浏览器的dom渲染发生在任务之间。
- 微任务按次序执行,并且
- 在每个回调后执行,只要没有别的js正在执行则执行
- 在每个任务的末尾执行。