Mansour
Mansour

Reputation: 1810

Avoid loading a CSS resource when JS is enabled without use of <noscript>

This question may sound familiar but not quite the same as asked before.

I have a CSS that is sent to browsers with no javascript functionality (referenced by a link tag). I have another CSS which is used by the ajax version of the site and is injected to the page by JS. Each of these files are relatively big (gt 200K). I don't want the JS enabled clients to download both files. I can do this easily using noscript tag. But that has the limitation in cases where the user is behind a proxy that filters script tags. So the browser ends up with no CSS altogether.

<html>
<head>
<noscript><link rel="stylesheet" type="text/css" href="nojs.css" /></noscript>
<script>
document.write('<link rel="stylesheet" type="text/css" href="js.css" />');
</script>
</head>
<body></body>
</html>

My attempt to use HTML comments in a non-standard way worked in Chrome but failed in FF:

<html>
<head>
<script>
document.write('<link rel="stylesheet" type="text/css" href="js.css" />');
document.write('<!----');
</script>
<link rel="stylesheet" type="text/css" href="nojs.css" /><!-- -->
</head>
<body></body>
</html>

Both browsers parse the HTML correctly (not sure if IE and Opera would too), but FF downloads the nojs.css in all cases (without actually applying it when JS is enabled).

Any ideas?

Upvotes: 0

Views: 147

Answers (1)

Julian D.
Julian D.

Reputation: 5463

The prefetching mechanism of Firefox seems to ignore the comment and preloads the CSS file, but only if it's referenced as a link element.

Use a CSS import statement instead to suppress prefetching of the unused file:

<html>
  <head>
    <script>
      document.write('<link rel="stylesheet" type="text/css" href="js.css" />');
      document.write('<!--');
    </script>
    <style>
      @import url(nojs.css)
    </style>
    <!-- -->
  </head>
<body>
...

Upvotes: 3

Related Questions