开发者

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

开发者 https://www.devze.com 2023-02-14 08:13 出处:网络
I need to ch开发者_JAVA百科eck if browser JavaScript is off, then display a error div instead of the body, how can I do this?You\'ll need to do it the other way around - so to speak - you\'ll have to

I need to ch开发者_JAVA百科eck if browser JavaScript is off, then display a error div instead of the body, how can I do this?


You'll need to do it the other way around - so to speak - you'll have to output everything, and then hide/ remove the error div using Javascript.

It's called Progressive Enhancement.


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

Of course, this is usually a bad idea, but I hope you've already considered that.


in the body you can add :

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


@roryf's solution is a good approach, although it is dependent on jQuery, and if the domloaded event fires a little late you can get a 'flash' of the no-js content.

The following will remove the html.no-js class before the body has rendered:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号