Adding a class with JavaScript, The Results

I god damn changed my mind, yes I did.

Yesterday I wrote about how I'm adding a HasJS class to the HTML element in my designs rather than swapping out a no-js class or removing a no-js class.

i'd originally thought that the best way (well the only way I originally thought of) was to add -

$("html").addClass("hasJS");

to my script.js of my (work in progress) personal, personable boilerplate.

Soon after realising that blogpost to the world Mark Perkins added a comment saying that add this -

<script>document.getElementsByTagName('html')[0].className += ' hasJS';</script>

added in the head would be a better/quicker way of doing it. I also had a couple of comments via the twitters saying this too.

Testing, Testing...1, 2, 3

So I decided today that what better way to spend a Friday evening that test those two bits of code with JSPerf. Now, in all honesty, I don't know what I'm doing. But, Sshhhh!!!. So I managed to find a test that already tested the performance for JavaScript to add a class with jQuery and 'Modern Javascript'. I thought this was perfect and also added the code that Mark offered and ran some tests. 

Whaaaatt???

Whilst I was testing all the browsers I've got on my MBA I thought it best to open up my Parallels VMWare and run it in IE9 (to start). Here's where I hit a problem with one of the tests. So I thought I'd do what I often do 'Ask Jack'

He pointed to a Mozilla Dev page which shows that IE (until v10) doesn't support -

classList

On that page is a nice polyfill for IE8 and up so I 'shoved' that into that test code and re-ran the tests. 

Near the finish line...

Here's the results for the test I re-ran with the polyfill included. 

As you can see the modern JS approach is quickest by miles. So I've decided (subject to change) that I'm now going to include -

document.querySelector('html').classList.add('js');

into the HEAD of my personal, personable boilerplate.

Just one more thing

You may noticed that I've also ditched .hasJS for just .js for my class name. This was spurred on from a brief couple of tweets with Matt Wilcox that made me decide that losing those three charecters will shave at least a little off my stylesheet file size. Every little helps and all that. That's about it for this post. You know, tomorrow is a different day. I may change my mind all over again. I'm currently trying to work out how to conditionally load the polyfill if classList is not supported. Until then, good 'morrow