Tutorial – Swapping CSS with JavaScript

Do you have some cool JavaScripts or maybe you’re using some jQuery and they come with their own CSS (Cascading Style Sheets)? What happens when you disable JavaScript how does your website look? Well if it is anything like a website I recently built that has heavy JavaScripts and jQuery it looks very different when JavaScript is disabled and the CSS is setup to give it the look and feel when JavaScript is enabled.

The easiest way that I’ve found to fix this issue is simply to have 2 CSS files one for when the website loads with JavaScript and one for when it doesn’t have JavaScript loaded. To do this properly you’ll need to have the CSS file for JavaScript being disabled to be loaded first and then swap it out with the JavaScript version when JavaScript is enabled. Now here’s how to do just that so that it works on your website.

This code needs to go in your < head > area.


Now you’ll notice there’s a bit going on the first thing you should notice is that the < link > which is loading the CSS has an “id” tag. This is the key to making this work as the JavaScript is looking for that “id”. When the script finds the “id” it will replace the location in the “href” which means it will load a different CSS.

The reason this works so well is that if JavaScript is disabled the script will never execute and the CSS that is designed to work with your website having JavaScript will execute. Otherwise the CSS for the JavaScript version of the website will replace the CSS.

Leave a Reply