requestIdleCallback 示例
通过具体例子,来理解浏览器性能优化相关的api,即requestIdleCallback.
示例一
/**
* 原文网站
* https://www.cnblogs.com/galenyip/p/4856996.html
*/
var eventsToSend = [];
var isRequestIdleCallbackScheduled = false;
function onNavOpenClick() {
// animate the menu
document.body.classList.add('open');
eventsToSend.push({
category: 'button',
action: 'click',
label: 'nav',
value: 'open'
});
schedulePendingEvents();
}
function schedulePendingEvents() {
if (isRequestIdleCallbackScheduled)
return;
isRequestIdleCallbackScheduled = true;
if ('requestIdleCallback' in window) {
requestIdleCallback(processPendingAnalyticsEvents, { timeout: 2000 });
} else {
processPendingAnalyticsEvents();
}
}
function processPendingAnalyticsEvents(deadline) {
isRequestIdleCallbackScheduled = false;
if (typeof deadline === 'undefined') {
deadline = { timeRemaining: function() { return Number.MAX_VALUE } };
}
while (deadline.timeRemaining() > 0 && eventsToSend.length > 0) {
var evt = eventsToSend.pop();
// 耗时操作
console.log(evt);
}
if (eventsToSend.length > 0) {
schedulePendingEvents();
}
}
示例二
/**
* 原文网站
* https://www.cnblogs.com/galenyip/p/4856996.html
*/
var elementsToAdd = [];
var documentFragment;
var isVisualUpdateScheduled = false;
function onAddButtonClick() {
elementsToAdd.push({
tag: 'div',
content: new Date().getTime()
});
scheduleElementCreation();
}
function scheduleElementCreation() {
if ('requestIdleCallback' in window) {
requestIdleCallback(processPendingElements, { timeout: 2000 });
} else {
processPendingElements();
}
}
function processPendingElements(deadline) {
if (typeof deadline === 'undefined') {
deadline = { timeRemaining: function() { return Number.MAX_VALUE } };
}
if (!documentFragment) {
documentFragment = document.createDocumentFragment();
}
while (deadline.timeRemaining() > 0 && elementsToAdd.length > 0) {
var elToAdd = elementsToAdd.pop();
var el = document.createElement(elToAdd.tag);
el.textContent = elToAdd.content;
documentFragment.appendChild(el);
// Don't append to the document immediately, wait for the next
// requestAnimationFrame callback.
scheduleVisualUpdateIfNeeded();
}
if (elementsToAdd.length > 0) {
scheduleElementCreation();
}
}
function scheduleVisualUpdateIfNeeded() {
if (isVisualUpdateScheduled)
return;
isVisualUpdateScheduled = true;
requestAnimationFrame(appendDocumentFragment);
}
function appendDocumentFragment() {
isVisualUpdateScheduled = false;
// Append the fragment and reset.
document.body.appendChild(documentFragment);
documentFragment = null;
}
至此,结束。