Only apply CSS rules when JavaScript is disabled

Sometimes there is CSS that should only apply when JavaScript is disabled. The lazy loading plugin Lazy Loader, for example, hides the images with the lazyload class, if JS is not active.

Until now I implemented that with a class that was added via JS to the html or body element. Without the class, the images are hidden, and if the class is present, the images are displayed.

Now the user wprox showed me an alternative solution in the W.org support forum, that he got from the article »Nice and easy lazy loading with lazysizes.js« by Steve McKinney: Simply put the styles for disabled JS into a noscript element.

So instead of adding a class via JS to an element, and use that class in CSS to overwrite styles for disabled JavaScript, this is what it looks like in my plugin now:

<noscript> <style> .lazyload { display: none; } </style> </noscript>
Code language: HTML, XML (xml)

If you think about it, that is an obvious solution, but it never came to my mind before.

Leave a Reply

Your email address will not be published. Required fields are marked *