$nextTick 源码解读与原理分析

1,184 阅读1分钟

Vue 的 nextTick 函数大家都不陌生,做什么的:
将注入的回调函数,以微任务的形式放到本次事件循环队列的末尾上去,如果不支持就放到下一次事件队列中

本文以 vue 2.x 最后一个版本(2.6.14)讲解源码

第一步: 创建flushCallbacks回调函数执行器

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]()
  }
}

callbacks用于存储$nextTick传入的函数
flushCallbacks用于遍历执行回调函数

第二步: 创建微任务包装器,并判断浏览器支持的微任务API赋予timerFunc

// Here we have async deferring wrappers using microtasks.
// In 2.5 we used (macro) tasks (in combination with microtasks).
// However, it has subtle problems when state is changed right before repaint
// (e.g. #6813, out-in transitions).
// Also, using (macro) tasks in event handler would cause some weird behaviors
// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
// So we now use microtasks everywhere, again.
// A major drawback of this tradeoff is that there are some scenarios
// where microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690, which have workarounds)
// or even between bubbling of the same event (#6566).
let timerFunc

由vue源码注释第一句,意思是:这里我们有使用微任务的异步延迟包装器。

  1. 先判断浏览器是否支持Promise,如果支持,则使用Promise来实现
if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  timerFunc = () => {
    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)
  }
  isUsingMicroTask = true
}

此处 Promise.resolve()
等价于 new Promise(resolve => resolve())
then函数注册回调

  1. 在判断浏览器是否支持MutationObserver,如果支持,则使用MutationObserver来实现
else if (!isIE && typeof MutationObserver !== 'undefined' && (
  isNative(MutationObserver) ||
  // PhantomJS and iOS 7.x
  MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
  // Use MutationObserver where native Promise is not available,
  // e.g. PhantomJS, iOS7, Android 4.4
  // (#6466 MutationObserver is unreliable in IE11)
  let counter = 1
  const observer = new MutationObserver(flushCallbacks)
  const textNode = document.createTextNode(String(counter))
  observer.observe(textNode, {
    characterData: true
  })
  timerFunc = () => {
    counter = (counter + 1) % 2
    textNode.data = String(counter)
  }
  isUsingMicroTask = true
} 

MutationObserver API在MDN描述是:
提供了监视对DOM树所做更改的能力,它会在指定的DOM发生变化时被调用。

vue是创建一个文本节点,通过监听文本节点变化来执行MutationObserver的注册函数调用
至于vue这么做的原理是什么,和MutationObserver监听DOM的变化和微任务又有什么联系?
请看我对MutationObserver的详解(编写中)

  1. 如果浏览器对上述微任务API都不支持,则使用setImmediate/setTimeout来异步执行回调
else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  // Fallback to setImmediate.
  // Technically it leverages the (macro) task queue,
  // but it is still a better choice than setTimeout.
  timerFunc = () => {
    setImmediate(flushCallbacks)
  }
} else {
  // Fallback to setTimeout.
  timerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

vue 源码说setImmediate是一个更好的选择相比setTimeout,因为性能高于setTimeout
但setImmediate目前只有最新版本的 Internet Explorer 和Node.js 0.10+实现了该方法

  1. 判断出浏览器支持的API后,最后一步便是执行
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
    timerFunc()
  }
  // $flow-disable-line
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}

导出nextTick方法,可接受两个参数cb是回调函数,ctx执行上下文
首先判断cb是否存在,存在则将绑定了ctx的回调函数push入callbacks中
pending默认值false,然后调用timerFunc微任务包装器来执行我们传入的回调

总结

  • $nextTick微任务包装器的shim降级顺序:
    Promise > MutationObserver > setImmediate > setTimeout
    (Tips: 尤大在2.x多个版本中多次改变shim的顺序,最终在2.x latest版本中定为此顺序)