Implementing Unobtrusive Javascript

泪湿孤枕 提交于 2019-12-04 18:46:35

basically you can insert a class "no-js" in your html element, like so

<html class="no-js" lang="en">

and if javascript is enabled on the client you soon remove that class (using modernizr or a simpler code snippet like

<head>
    <script>
    (function(d) { 
         d.className = d.className.replace(/(^|\b)no-js(\b|$)/, 'js');
    }(document.documentElement));
    </script>
    ...
</head>

in this way you can avoid the FOUC (flash of unstyled content) simply using .no-js and .js class in the css rules like so:

.yourlistitems { 
   display: block; 
}
.js .yourlistitems { 
   display: none; 
}

this approach is also used by H5BP
Note that you don't really need to prepend .no-js class to each rule: thinking in terms of "progressive enhancement" and "unobtrusive javascript" you will code and style first for a page that also works without javascript, then you will add functionality (and style specificity, prepending the .js class)

Sam Greenhalgh

Have you thought about using a method like the one implemented with Modernizr?

CSS classes are added to the HTML tag by a script that causes different CSS selectors to match.

<html>
<head>
    <!--
    Putting this script in the head adds the "js" 
    class to the html element before the page loads.
    -->
    <script type="text/javascript" language="javascript">
        document.documentElement.className = "js";
    </script>
    <style type="text/css">
        /*
        Only apply the hidden style to elements within the HTML element
        that has the js class
        */
        .js .description {display:none;}
    </style>
</head>
<body>
    <span class="description">Example</span>
</body>
</html>

Can't tell if this really helps because of potential asynchronous operations but you might add a <script> which prepends your <style> with display: (block|inline|whatever) in which you toggle all relevant display to none !important by using plain JS, not jQuery.

So in case of JS the CSS display setting will be overridden beforehand.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!