Search code examples
javascripthtmlcssnoscript

How to link external stylesheet only if javascript is enabled


I have a page that I want to be styled differently depending on whether javascript is enabled or not.

code:

<link rel="stylesheet" href="./css/main.css" type="text/css" />

<noscript>
    <link rel="stylesheet" href="./css/noscript.css" type="text/css" />
</noscript>

My problem is that noscript.css only overwrites some attributes, not all. So since main.css have a lot more styling in it it also applies. Only styles that are overwritten looks good. If I remove the link to main.css the page looks as I want it.

Is there any way to "reset" all previous style to default, or disable the link to main.css on noscript?

Thank you!


Solution

  • You could do this:

    <script>
      document.write('<link rel="stylesheet" href="./css/main.css" type="text/css" />');
    </script>
    <noscript>
        <link rel="stylesheet" href="./css/noscript.css" type="text/css" />
    </noscript>
    

    I'm normally not a huge fan of document.write(), but this is an example of it being the simplest thing to do. You could of course create the <link> tag and append it to the <head> or whatever if it's too distasteful.