由于在github用javascript实现了一下promise的简单功能。但是其中nextTick的实现主要是借助immediate包
所以一直想找一个机会总结一下nextTick在浏览器中如何实现。
只要环境允许,优先使用顺序靠前的
1.MutationObserver
var Mutation = window.MutationObserver || window.WebKitMutationObserver;
exports.install = function (handle) {
var called = 0;
var observer = new Mutation(handle);
var element = global.document.createTextNode('');
observer.observe(element, {
characterData: true
});
return function () {
element.data = (called = ++called % 2);
};
};
触发dom变动,借助MutationObserver回调函数,从而实现了nextTick
2.messageChannel
MDN: Channel Messaging API的Channel Messaging接口允许我们创建一个新的消息通道,并通过它的两个MessagePort 属性发送数据。
function (func) {
var channel = new window.MessageChannel();
channel.port1.onmessage = func;
return function () {
channel.port2.postMessage(0);
};
};
3.stateChange
在dom文档中插入script文件,当script文件添加完成时,触发回调函数
function () {
// Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
var scriptEl = global.document.createElement('script');
scriptEl.onreadystatechange = function () {
handle();
scriptEl.onreadystatechange = null;
scriptEl.parentNode.removeChild(scriptEl);
scriptEl = null;
};
global.document.documentElement.appendChild(scriptEl);
return handle;
};
网友评论