Implementing Unobtrusive Javascript

Implementing Unobtrusive Javascript

本文关键字:Javascript Unobtrusive Implementing      更新时间:2023-09-26

我正在重新设计一个旧网站,并专注于使Javascript/jQuery尽可能不引人注目。我正在就项目的一部分寻求一些建议:UJ要求,如果浏览器中关闭Javascript,用户仍然可以使用所有网站内容。我的网站有一个很大的项目列表。列表中的每个项目都有自己的描述,默认情况下使用CSS display:none来隐藏它。点击该项可以使用jQuery.thoggle():切换描述的可见性,所以一个无法使用Javascript(无论出于何种原因)的人永远不会看到它。如果我使用Javascript/jQuery而不是CSS来隐藏描述,那么当页面加载时,它们都会立即可见,我希望避免这种情况。那么,什么是最好的解决方案呢?

基本上,您可以在html元素中插入一个类"no-js",就像一样

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

如果在客户端上启用了javascript,那么很快就会删除该类(使用modernizr或类似的更简单的代码片段

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

通过这种方式,您可以简单地使用css规则中的.no-js.js类来避免FOUC(未格式化内容的闪烁),如:

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

H5BP也使用这种方法
请注意,您并不真的需要为每个规则预先准备.no-js类:从"渐进增强"answers"不引人注目的javascript"的角度考虑,您将首先为没有javascript也能工作的页面编写代码和样式,然后添加功能(以及样式特定性,预写.js类)

您有没有想过使用类似Modernizr实现的方法?

CSS类是通过一个脚本添加到HTML标记中的,该脚本会使不同的CSS选择器匹配。

<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>

由于潜在的异步操作,无法判断这是否真的有帮助,但您可以添加一个<script>,它在<style> with display: (block|inline|whatever)之前,您可以使用纯JS而不是jQuery将所有相关显示切换到none !important

因此,在JS的情况下,CSS显示设置将被预先覆盖。