简体   繁体   中英

<noscript> tag not working

I've used the <noscript> tag to hide certain elements when javascript is not enabled; however, it doesn't seem to work.

My document declaration:

<!DOCTYPE html>

At the end of my file I typed the following:

<noscript>
 <style type="text/css" scoped> #status {display:none;} </style> 
</noscript>

</body>
</html>

But the #status div is still present even after disabling JS. Am I missing something here?

Remove the scoped attribute of the style tag. It's making your CSS apply strictly to the <noscript> tag.

If this attribute is present, then style applies only to its parent element.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style#Attributes

A simpler to manage solution would be to make the element hidden by default and use this :

<script>document.getElementById('status').style.display='block';</script>

(or an equivalent class based solution)

Try removing the scope of the style , like the code below.

       <noscript>
           <style type="text/css"> #status {display:none;} </style> 
       </noscript>

@dystroy's answer is the right way of doing it, because:

  • <style> elements can't be placed on <body> (except if they have scoped attribute)
  • <noscript> elements can't be placed on head.

But if you don't want a delay, you can use the following in <head> :

<style id="noScriptSheet" type="text/css">
.onlyScript{ display:none;}
</style>

<script type="text/javascript">
function kill(el){
    return el.parentNode.removeChild(el);
}
kill(document.getElementById('noScriptSheet'));
</script>

And add a class to your element:

<div class="onlyScript">Hello world!</div>

Demo : http://jsfiddle.net/TQLfu/

I am adding this answer because this seems to be the most popular SO-question regarding the noscript tag.

It doesn't seem to fire at all with "Sybu JavaScript Blocker" . So in case you are testing with that JavaScript blocker try using another JavaScript blocker . When I used "Toggle Javascript" the noscript tag fired without problem. I did not yet discover a way to detect that "Sybu JavaScript Blocker" is being used.


My Testing environment:

  • Sybu JavaScript Blocker, Version 2.93
  • Toggle JavaScript, Version 1.3
  • Chrome, Version 85.0.4183.83

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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