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

假如想象 提交于 2019-12-08 02:36:14

问题


I need to check if browser JavaScript is off, then display a error div instead of the body, how can I do this?


回答1:


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




回答2:


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.




回答3:


in the body you can add :

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



回答4:


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


来源:https://stackoverflow.com/questions/5140388/how-to-detect-if-browser-javascript-is-off-and-display-a-notice

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