Valid way to add noscript in head for wrapping redirect Valid way to add noscript in head for wrapping redirect javascript javascript

Valid way to add noscript in head for wrapping redirect


I am not sure why you need to redirect to another page instead of just showing a message. I use JS and a little CSS to handle these situations for me. Something like this:

<head>   ....   <script type="text/javascript"> document.documentElement.className += " js"</script>   <link rel="stylesheet" type='text/css' href="css/layout.css" media="all" /></head><body>    <div id="noscript">Please enable JavaScript, then refresh this page. JavaScript is required on this site</div>    <div id="wrapper">       ...    </div></body>

Then in layout.css:

 #wrapper      { display: none  } /* Hide if JS disabled */ .js #wrapper  { display: block } /* Show if JS enabled */ .js #noscript { display: none  } /* Hide if JS enabled */

By doing it this way, the class is applied to the html element before the page is rendered so you won't get a flicker as the non-JS content is swapped out for the JS content.


Doug's solution is pretty good, but it has a few drawbacks:

  • It is not valid to have a class attribute on the html element. Instead, use the body.
  • It requires that you know what display type to set the element to (i.e. ".js #wrapper { display: block }").

A simpler, more valid and flexible solution using the same approach could be:

<html>    <head>        <!-- put this in a separate stylesheet -->        <style type="text/css">            .jsOff .jsOnly{                display:none;            }        </style>    </head>    <body class="jsOff">        <script type="text/javascript">            document.body.className = document.body.className.replace('jsOff ','');        </script>        <noscript><p>Please enable JavaScript and then refresh the page.</p></noscript>        <p class="jsOnly">I am only shown if JS is enabled</p>    </body></html>

With this, it's valid html (no class attribute on the html element). It is simpler (less CSS). It's flexible. Just add the "jsOnly" class to any element that you want to only display when JS is enabled.


The <noscript> tag cannot be in the <head>, it must be in the <body>

The common practice is to show a message instead of redirecting, as there is no way to redirect only if javascript is disabled.

You could do it the other way around, have the first page be nojs.html, and on that page use javascript to redirect to the main content.