Last active
September 17, 2017 20:27
-
-
Save xnimorz/ad6da6d06916a2f3d0be71ec9b1780f3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Наш модуль сможет работать как в node.js, так и в браузере | |
(function (global) { | |
if (global.setImmediate) { | |
return; | |
} | |
// оборачиваем присваивание в анонимную функцию, чтобы один раз найти нужный способ асинхронного вызова для платформы и использовать его. | |
global.setImmediate = (function() { | |
var list = []; | |
var addFunction = function(fn) { | |
return list.push(fn) - 1; | |
}; | |
var callList = function() { | |
var store = list; | |
var length = store.length; | |
var i = 0; | |
list = []; | |
while (i < length) { | |
store[i++](); | |
} | |
}; | |
// nodejs < 0.10 | |
if (typeof process === 'object' && process.nextTick) { | |
return function(fn) { | |
addFunction(fn) || process.nextTick(callList); | |
}; | |
} | |
// Используем microtask queue. Если в приложении критично использовать только macrotask queue, данную часть полифила нужно удалить | |
var MutationObserver = global.MutationObserver || global.WebKitMutationObserver; | |
if(MutationObserver) { | |
var num = 1; | |
var node = document.createTextNode(''); | |
new MutationObserver(callList).observe(node, { characterData : true }); | |
console.log('here!') | |
return function(fn) { | |
addFunction(fn) || (node.data = (num *= -1)); | |
}; | |
} | |
if (global.postMessage) { | |
var postMessageIsAsynchronous = true; | |
var oldOnMessage = global.onmessage; | |
global.onmessage = function() { | |
postMessageIsAsynchronous = false; | |
}; | |
global.postMessage('', '*'); | |
global.onmessage = oldOnMessage; | |
if (postMessageIsAsynchronous) { | |
var messageFlag = '__unique-name__' + new Date().getTime(); | |
var processMessage = function(e) { | |
if (e.data !== messageFlag) { | |
return; | |
} | |
e.stopPropagation && e.stopPropagation(); | |
callList(); | |
}; | |
if (global.addEventListener) { | |
global.addEventListener('message', processMessage, true); | |
} else { | |
global.attachEvent('onmessage', processMessage); | |
} | |
return function(fn) { | |
addFunction(fn) || global.postMessage(messageFlag, '*'); | |
}; | |
} | |
} | |
return function(fn) { | |
addFunction(fn) || setTimeout(callList, 0); | |
}; | |
})() | |
})(typeof window !== 'undefined'? window : global); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment