Detecting Javascript on pageload to preempt slow jQuery

jQuery is great, but sometimes on some browsers/devices it can be pretty slow to be implemented and take effect. I'm looking at you iPad/iPhone!

Why is this such a problem?

In the case I came across this was a problem because the jQuery .hide() I was using was acting after the DOM was loaded and the iPad was slow to do this. It was creating a noticable 'pop' when the page was loaded before elements then disappeared. Not the end of the world, but annoying. I asked on stackoverflow and this is the best solution that was provided, not to mention being a bit of genius.

It works by applying the class to the document if javascript is present, otherwize the hide class is not applied and we get a nicely enhanced page for the javascript users.

You will need to put in javascript tags in the head of the document:

document.documentElement.className = 'js';

Then add this to your css, and target any of the elements you want to hide stright away on detection of javascript. This can be in your normal css file or in the head of the document so it is loaded before the rest of the page.

.js #element{display:none;}

It is an incredibly simple and clever solution.

Published on

Filled under

Discuss!

comments powered by Disqus