Using .no-js class to detect js

I always used the method of having the .no-js class in the tag <html>, and then using modernizr, which breaks the tag and replaces it with js if JavaScript is enabled in the user browser.

Basically, I created CSS3 mobile and desktop navigation. I have styles to change its behavior if there are CSS transitions, etc. (Tested with modernizr), and also if there is js or no-js.

The problem is that I get a flash version of no-js before JavaScript can load and change the class to js. (since the default class is non-js)

I cannot figure out how to find a fix for this. If I put js specific code as main classes, then specify another with the prefix .no-js, it blinks no-js, even if js is on. If I switch it, he will do the same ...

I may be stupid, but any pointers would be great.

+5
source share
2 answers

Paul Irish has a great blog post about fixing this issue. Here is the solution from this post:

<!DOCTYPE html>
<html lang='en' class='no-js'>
    <head>
        <script>(function(H){H.className=H.className.replace(/\bno-js\b/,'js')})(document.documentElement)</script>
        ...

The key is to make sure that you update the class names before the browser is able to display anything.

+8
source

You can add a short script to the very top <head>:

<script>
  document.documentElement.className =
    document.documentElement.className.replace('no-js', 'js');
</script>

<noscript>, JavaScript.

+5

All Articles