What is the purpose of the HTML “no-js” class?

后端 未结 7 1160
误落风尘
误落风尘 2020-11-27 08:59

I notice that in a lot of template engines, in the HTML5 Boilerplate, in various frameworks and in plain php sites there is the no-js class added onto the

相关标签:
7条回答
  • 2020-11-27 09:43

    The no-js class is used by the Modernizr feature detection library. When Modernizr loads, it replaces no-js with js. If JavaScript is disabled, the class remains. This allows you to write CSS which easily targets either condition.

    From Modernizrs' Anotated Source (no longer maintained):

    Remove "no-js" class from element, if it exists: docElement.className=docElement.className.replace(/\bno-js\b/,'') + ' js';

    Here is a blog post by Paul Irish describing this approach: http://www.paulirish.com/2009/avoiding-the-fouc-v3/


    I like to do this same thing, but without Modernizr. I put the following <script> in the <head> to change the class to js if JavaScript is enabled. I prefer to use .replace("no-js","js") over the regex version because its a bit less cryptic and suits my needs.

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

    Prior to this technique, I would generally just apply js-dependant styles directly with JavaScript. For example:

    $('#someSelector').hide();
    $('.otherStuff').css({'color' : 'blue'});
    

    With the no-js trick, this can Now be done with css:

    .js #someSelector {display: none;}
    .otherStuff { color: blue; }
    .no-js .otherStuff { color: green }
    

    This is preferable because:

    • It loads faster with no FOUC (flash of unstyled content)
    • Separation of concerns, etc...
    0 讨论(0)
提交回复
热议问题