3. Loose event handling on large set
Same as earlier, but using promises and createDocumentFragment
Google Chrome 219.635 µ seconds
by Renoir Boulanger
HTML
<p>
Last clicked item is <code id="lastClicked">None</code>
</p>
<ul></ul>
CSS
div {opacity:0;transition: opacity 1s;}
div.show { opacity:1;}
JavaScript
let maxIter = 80000;
var t0 = window.performance.now();
function clickHandler(evtObj) {
let innerText = evtObj.target.innerText
, lastClicked = document.querySelector('#lastClicked') || 'None';
lastClicked.innerText = innerText;
/**
* Nothing fancy, just a notifier copy-pasta from MDN
* https://developer.mozilla.org/en-US/docs/Web/API/notification
**/
if (!!("Notification" in window)) {
if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
var notification = new Notification(`Last clicked was ${innerText}`);
}
});
}
}
}
function createListElement(i, textTemplate=`Item `) {
let innerText = textTemplate + Number(i)
, frag = document.createElement('li');
frag.textContent = innerText;
return frag;
}
/** ============= Building things now ================= **/
let list = document.querySelector('ul')
, elements = Array(Number(maxIter)).fill('Foo ')
, out = document.createDocumentFragment();
list.addEventListener("click", clickHandler, {}, true);
elements
.forEach( (str, idx) => {
out.appendChild(createListElement(idx, str));
});
list.appendChild(out);
/** ============ Performance timing ============ **/
var t1 = window.performance.now()
, calc = Number(t1) - Number(t0)
, calcText = `took ${calc} seconds`
, calcFrag = document.createElement('p');
calcFrag.textContent = calcText;
document.querySelector('#lastClicked').parentNode.insertBefore(calcFrag, null);