I was cleaning up some javascript notifications for a website and came across this common question: what is the best way for elements to be visible when a user does not have javascript enabled but hidden when they do (often to be revealed by javascript?
I cam across an article titled How To Hide And Show Initial Content, Depending On Whether JavaScript Support Is Available which was great reading on the subject. There were 3 methods that stood out in the article and comments.
- Use a javascript file sourced in the head section to include a css stylesheet file specifically for javascript enabled browsers. The downsides of this method are 2 extra requests on the initial visit and needing to keep all javascript css in a separate css file.
- A method detailed in The best way to hide content by JavaScript is to attach a class to the html element. This is a violation of the spec and therefore may not be cross browser compatible but seems to be used by a number of people without problem.
- By adding a 1 line script immediately after the body tag that sets the body class to “js” or something else indicating the presence of javascript. The chief objection to this is that setting the body class could trigger a re-rendering.
At the moment I’m trying option 3. My reasoning is that it is the most simple to implement and maintain. The concern that it could cause a re-rendering seems minimal to me. Presumably since the parser proceeds linearly through the html than this change should occur before much else and thus not lead to any visible flicker. However, real world testing may be the only way to discern if any of these methods are superior to the others.