2

Given a web page with input fields, does it have a performance difference whether or not you assign the onblur handler inside of the onfocus handler like so:

var inputFields = document.querySelectorAll("input");

for (i = 0; i < inputFields.length; ++i) {
    var thisInput = inputFields[i];

    thisInput.onfocus = function(){

        console.log("input received focus");

        this.onblur = function(){

            console.log("input lost focus");
            thisInput.onblur = null;

        }//end onblur handler

    }//end onfocus handler  

}//end for loop

My thought was that this would only add the blur event when the input event received focus and that the blur handler could be removed when the blur processing was done. I thought perhaps this would improve efficiency since there are less event handlers attached at a given time versus assigning all input fields the onblur handler at setup. Are there any caveats to setting up the code this way? If it matters, this will be used in a firefox extension.

Eric G
  • 129
  • 3
  • 3
    Have you done any testing to see the difference in performance by using only one handler instead of two? What results did you get? – Adam Zuckerman Jan 14 '15 at 00:30
  • I would expect that, for standard events, having a handler attached when it won't be called is more efficient than constantly attaching/detaching handlers. But what do your measurements say? – Bart van Ingen Schenau Jan 14 '15 at 08:56
  • Any recommendations on the type of testing that would be most meaningful and how to accurately perform it? – Eric G Jan 16 '15 at 04:15
  • 2
    I said it on SO yesterday and I'll say it again here...context is *crucial* when discussing performance issues. All you've told us is that this is going into a Firefox extension. I wouldn't be worrying about [micro-optimization](https://softwareengineering.stackexchange.com/a/99466/308851) until you have solid metrics and a reason to target this piece of code. At this point in time, *it doesn't matter*. – Dan Wilson Sep 18 '18 at 12:24

3 Answers3

1

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.

Greg Burghardt
  • 34,276
  • 8
  • 63
  • 114
0

does it have a performance difference.

I thought perhaps this would improve efficiency since there are less event handlers attached at a given time versus assigning all input fields the onblur handler at setup

No it won't. Having lots of attached events that never actually gets called won't make handling of other events slower.

Having attached events may increase memory usage, but unless you're attaching to thousands of elements, the increase in memory usage is usually negligible. If you do need to do attach to thousands of elements for some reason, do consider using event delegation instead.

Lie Ryan
  • 12,291
  • 1
  • 30
  • 41
-2

Focus always fires blur and blur always fires focus, so you cannot separate them in any way. In addition, native mouse and keyboard events are asynchronous, so they cannot block like a custom event created programmatically via dispatchEvent:

Unlike "native" events, which are fired by the DOM and invoke event handlers asynchronously via the event loop, dispatchEvent invokes event handlers synchronously. All applicable event handlers will execute and return before the code continues on after the call to dispatchEvent.

Here is the logic:

focusing on a focusable element fires a focus event at the element

focusing on a focusable element fires a blur event at the previous focused element

The document received focus by default, so this is always the case. Use the W3C tests for reference:

<script>
  var i1 = document.getElementById('i1'),
  i2 = document.getElementById('i2'),
  t1 = async_test("focusing on a focusable element fires a focus event at the element"),
  t2 = async_test("focusing on a focusable element fires a blur event at the previous focussed element");
  i2.onfocus = t1.step_func_done(function(e){
    assert_true(e.isTrusted, "focus event is trusted");
    assert_false(e.bubbles, "focus event doesn't bubble");
    assert_false(e.cancelable, "focus event is not cancelable");
    assert_equals(document.activeElement, i2);
  });
  i1.onblur = t2.step_func_done(function(e){
    assert_true(e.isTrusted, "blur event is trusted");
    assert_false(e.bubbles, "blur event doesn't bubble");
    assert_false(e.cancelable, "blur event is not cancelable");
  });
  i1.focus();
  i2.focus();
</script>

The User Timing API can be used to test performance.

References

Paul Sweatte
  • 382
  • 2
  • 15