Theme support for single page application in javascript

I would like to add a theme support to my single page application. The requirement is that the theme change must be done locally by javascript (no server calls) to be used in offline mode. I use angularjs, so html will be changed in the router.

The only problem that I have, is how to treat css. Is there any js library to help me load css files? Are there any problems involved in that?

EDIT: I have found the following library https://github.com/rgrove/lazyload/ which should do the job of loading css files. The only downside of the library is that the last update of the library is more than one year ago. A more actively developed library would be appreciated.

style elements can be added and removed in JavaScript. Simply create the element and add it to the page to apply the rules therein, and remove the element to remove its rules. You can do the same with link elements referring to external stylesheets, but if you want to be sure to work in offline mode and if the sheet may not have been cached, style elements with inline rules might work better.

Here's an example using a style element:

(function() {
  var css = "body { color: green; }";

  document.getElementById("theButton").onclick = toggleStyle;

  function toggleStyle() {
    var style = document.getElementById("styleOne");
    if (style) {
      // Remove it
      style.parentNode.removeChild(style);
    }
    else {
      // Add it
      style = document.createElement('style');
      style.id = "styleOne";
      if (style.styleSheet) {
          style.styleSheet.cssText = css;
      }
      else {
          style.appendChild(document.createTextNode(css));
      }
      document.body.appendChild(style);
    }
  }

})();

Live Copy | Source

Using a link would be even easier, because you don't have to deal with browser differences around where the style text goes.

If your theme only change the color, what I will do is using different css class to address this issue. Since CSS can be overwrote, you just need to attach themename as a class to parent element, and create corresponding rule for it. I would suggest to put all theme related css rule in a different file, that will be easier to maintain.

like

.themename.cssclassname{
   color: red;
}

will trump

.cssclassname{
   color: green;
}

And you can use less to create nested rules easily

By doing this, you will have 3 benefits.

  1. All browsers accept this including IE7. (I think IE7 has some problems when you dynamically insert style tag)

  2. All CSS file will be cached.

  3. easy to maintain. (I really don't like mix CSS and JS together too much.)