The performance difference will be negligible. Technically the focus handler is doing extra work by attaching an event handler to the element, so performance should slow down, however I doubt this is a measurable difference.
If the number of event handlers is slowing the page down, JavaScript Event Delegation is a better response to the performance problems.
Focus and blur events are little tricky for event delegation. Newer browsers support the "focusin" and "focusout" events, which are bubbling versions of "focus" and "blur" respectively:
document.documentElement.addEventListener("focusin", handleFocus, false);
document.documentElement.addEventListener("focusout", handleFocus, false);
Older browsers only support "focus" and "blur" which do not bubble. You can still support those older browsers if they properly support addEventListener by attaching the handlers to the capturing phase of an event:
document.documentElement.addEventListener("focus", handleFocus, true);
document.documentElement.addEventListener("blur", handleBlur, true);
This means you attach 1 event handler per event at page load. The document.documentElement
property references the <html>
element, and is available the moment JavaScript begins executing, so no more waiting for the DOM to be "ready".
Then you just need to detect if the target of the event is an element you care about before doing work:
function handleFocus(event) {
if (event.target.nodeName !== "INPUT") {
return;
}
console.log("input received focus");
}
function handleBlur(event) {
if (event.target.nodeName !== "INPUT") {
return;
}
console.log("input lost focus");
}
So really, you are likely trying to solve the wrong performance problem.
The benefit you gain by attaching the "blur" event handler on focus is you do less work at page load to attach event handlers. You can mitigate this problem by utilizing event delegation instead.
And there is one more benefit to event delegation that isn't obvious. When dynamically adding elements to the page, either by calling appendChild(element)
or parsing HTML via element.innerHTML = "..."
you don't need to do any additional work to attach event handlers to the newly added<input>
elements. It really helps clean up and simplify your event handler code.