繁体   English   中英

如何检测浏览器JavaScript是否已关闭并显示通知

[英]How to detect if browser JavaScript is off and display a notice

我需要检查浏览器JavaScript是否已关闭,然后显示错误div而不是正文,我该怎么做?

你需要反过来做 - 可以这么说 - 你必须输出所有内容,然后使用Javascript隐藏/删除错误div。

它被称为渐进增强。

<html class="no-js">
    <head>
    <style>        
        .error,
        .no-js #container {
            display: none;
        }

        .no-js .error {
            display: block;
        }
    </style>

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

    </head>
    <body>
        <div id="container">
            rest of page
        </div>
        <div class="error">
            sorry, no javascripty, no sitey!
        </div>
    </body>
</html>

当然,这通常是一个坏主意,但我希望你已经考虑过了。

你可以添加身体:

<noscript>
      Here the html to display when javascript is off
</noscript>

@ roryf的解决方案是一个很好的方法,虽然它依赖于jQuery,如果domloaded事件稍晚发生,你可以获得no-js内容的'flash'。

以下将在正文渲染之前删除html.no-js类:

<!DOCTYPE html>
<html class="no-js">
<head>
<script>

if (document.documentElement) {
    var cn = document.documentElement.className;
    document.documentElement.className = cn.replace(/no-js/,'');
}

</script>
</head> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM