We need style sheets for our websites, we all do. Unless, of course it’s badly written HTML with CSS codes inline, we need style sheets to define all those CSS rules that make the website visually appealing.

Style sheets are generally easy to use. SEO experts from https://www.bluewhalemedia.co.uk/manchester/web-design-manchester/ profess that all you have to do is just link all your style sheets and you’re done. The contents of style sheet, actual CSS code, is off topic here. But there are many situations when you need to load these style sheets conditionally. Like when you want to show alternative theme for your website, or rendering CSS for particular browser only. In such situations simply linking style sheets won’t help much.

This is where dynamicStyles comes in play. It’s simple JavaScript library, created by me, to handle such a situations. Let’s see what it can do.

Load style sheets dynamically

Just create an array of style sheets you want to add and call in the init function, as given below –

var styles = [
    {path: "styles/bootstrap.min.css"},
    {path: "styles/common.css"},
    {path: "styles/one.css", title: "one"},
    {path: "styles/two.css", title: "two"},
    {path: "styles/three.css", title: "three"},

Note: we’ve title options for few style sheets. From here on, all the operation in dynamicStyles will happen on the style sheets which have title attribute set. Style sheets with no title attribute, will apply to page permanently.

Switch between themes

Switching theme is pretty simple too. You have two options here – either cycle through all applied style sheets (title attribute ones only), or set certain style sheet using it’s title name.


Set style sheet:


Remove Style Sheet

You can remove already applied style sheet (those are inserted by this library and have title attribute) as well. Just use title name to remove the style sheet


Interesting, isn’t it? Also, whatever style sheet you’ve selected, it’ll stay selected even after page refresh or even when you close and reopen the browser.

There is more features available with this library. You can see some examples here.
Also, head over to GitHub page for further usage, and documentation.