Implementing Unobtrusive Javascript

2019-04-16 04:10发布

问题:

I'm reworking an old website and am focusing on making the Javascript/jQuery as unobtrusive as possible. I'm looking for some advice on one part of the project: UJ requires that, if Javascript is turned off in a browser, all the site content is still available to the user. One part of my site has a large list of items. Each item in the list has it's own description, which uses CSS display:none to hide it by default. Clicking on the item toggles the visibility of the description using jQuery .toggle():, so a person unable to use Javascript (for whatever reason) would never see it. If I use Javascript/jQuery rather than CSS to hide the descriptions, they are all momentarily visible when the page loads, which I want to avoid. So what's the best solution?

回答1:

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)



回答2:

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>


回答3:

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.