skip to Main Content

I’ve got a div that’s intermittently hidden in my app.

<!-- Hidden -->
<div aria-hidden="true">...</div>

When making the div visible I omit the aria-hidden attribute, keeping the DOM clean and relying on the fact that the div is visible by default.

<!-- Visible -->
<div>...</div>

Is there any performance differential between the previous approach where I omit the attribute altogether, and the next approach where I change the attribute’s value to false?

<!-- Visible -->
<div aria-hidden="false">...</div>

I’m aware that if there’s a difference it’ll be small. Presumably still measurable, though. This is an academic question more than anything else.

2

Answers


  1. I added a test for this here: https://jsperf.app/fapozi

    Setting up the test with:

    <div id="demo" aria-hidden="true">
        demo element
    </div>
    
    const el = document.getElementById('demo');
    

    Test case 1 is:

    el.removeAttribute('aria-hidden');
    el.setAttribute('aria-hidden', 'true');
    

    Test case 2 is:

    el.setAttribute('aria-hidden', 'false');
    el.setAttribute('aria-hidden', 'true');
    

    Here are the results for Firefox and Chrome on my machine
    enter image description here

    enter image description here


    Results

    Apparently using removeAttribute is slightly faster!

    Login or Signup to reply.
  2. Removing an attribute is faster:

    Cycles: 1000000 / Chrome/117
    ---------------------------------------------------------
    attribute remove   449/min  1.0x  463  449  463  460  464
    attribute change   532/min  1.2x  547  541  532  545  553
    ---------------------------------------------------------
    https://github.com/silentmantra/benchmark
    
    <div id="el" aria-hidden="true">...</div>
    <script benchmark="1000000">
    
    // @benchmark attribute remove
    
    el.removeAttribute('aria-hidden');
    el.setAttribute('aria-hidden', 'true');
    '';
    
    // @benchmark attribute change
    el.setAttribute('aria-hidden', 'false');
    el.setAttribute('aria-hidden', 'true');
    '';
    
    </script>
    <script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search