對Vue裏$nextTick的思考

這個API的官方說明是:

在下次 DOM 更新循環結束之後執行延遲迴調。在修改數據之後立即使用這個方法,獲取更新後的 DOM。

這是怎麼做的呢?

Vue源碼裏有一個next-tick.js,源碼比較短,我們來仔細看一看:

/* @flow */
/* globals MutationObserver */

import { noop } from 'shared/util'
import { handleError } from './error'
import { isIE, isIOS, isNative } from './env'

export let isUsingMicroTask = false

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 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

// The nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore next, $flow-disable-line */
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
} 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
} 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)
  }
}

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實際上是把傳入的函數存到一個數組裏。然後根據環境情況,添加一個微任務或者宏任務來順序執行數組裏的函數。

代碼的註釋裏寫了,之前使用過一次宏任務,結果bug比較多。又換回了微任務。代碼來首先使用原生的Promise來添加微任務,如果沒有,就使用MutationObserver。如果兩個都沒有,就降級到宏任務。依次順序這樣的:

添加微任務

Promise

MutationObserver

添加宏任務

setImmediate

setTimeout

 

問題1

微任務和宏任務又啥區別呢?

我在網上找到下面這些圖片,對理解又很好的幫助:

藍色的代表宏任務,黃色的是微任務,灰色的是瀏覽器重新渲染UI界面。

那麼這兩個任務的區別就是,在每一次渲染界面之前,都會執行宏任務然後清空微任務隊列。爲了驗證這個過程,可以寫下面的代碼進行測試。

<template>
  <p id="test">{{ i }}</p>
</template>

<script>
export default {
  data () {
    return {
      i: 1
    }
  },
  components: {
    BookCard
  },
  mounted () {
    const time = new Date().getTime()
    Promise.resolve().then(() => {
      console.log('promise ' + document.querySelector('#test').innerHTML)
      while ((new Date().getTime() - time) < 1000 * 5) {
      }
    })
    this.i = 2
  }
}
</script>

上面代碼會輸出promise 2,卡住5秒之後,在瀏覽器裏才能看到數字1變成了2。這是因爲我們利用Promise在微任務裏卡了瀏覽器5秒,5秒以後瀏覽器纔會重新渲染界面。但是在渲染界面之前,dom節點已經更新了,這是因爲在微任務執行的時候,dom節點已經更新完畢了,這裏猜測Vue用於更新Dom的操作在這一輪循環的微任務最前面(也就是我們寫的Promise.resolve代碼之前,Vue應該就插入了一個用於更新Dom的微任務),但是這個時候瀏覽器還沒重新渲染頁面。

 

問題2

爲什麼添加了微任務和宏任務就能在Dom更新以後執行?

根據第一個問題的圖片,我們知道,如果在當前任務裏添加宏任務。那麼下一個循環週期,也就是重新渲染之後會執行(這個時候肯定是Dom更新以後執行的)。

那麼微任務呢,這應該是Vue保證的,在Vue生命週期或者事件函數裏添加微任務,微任務會在Dom更新後,瀏覽器重新渲染頁面前執行。所以猜測Vue每次會在執行用戶代碼之前先添加更新Dom的微任務。等我看看源碼再來和大家分享。

 

問題3

哪些函數能添加微任務,哪些函數能添加宏任務呢?

宏任務: setTimeout, setInterval, setImmediate, requestAnimationFrame, I/O
微任務: process.nextTick, Promises, Object.observe, MutationObserver

其中requestAnimationFrame,比較特殊

window.requestAnimationFrame() 告訴瀏覽器——你希望執行一個動畫,並且要求瀏覽器在下次重繪之前調用指定的回調函數更新動畫。該方法需要傳入一個回調函數作爲參數,該回調函數會在瀏覽器下一次重繪之前執行。這個函數實際測試,會在微任務之後,瀏覽器重新渲染界面之前執行。很多動畫庫都是利用了這個函數。

 

參考文章:

https://github.com/aooy/blog/issues/5

https://segmentfault.com/q/1010000017571945

https://stackoverflow.com/questions/25915634/difference-between-microtask-and-macrotask-within-an-event-loop-context

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章