3

I have read up on it and it seems like the best method to add a stylesheet using jQuery is the following:

 $('head').append('<link rel="stylesheet" type="text/css" href="../css/mystyle.css">');

Now what I would like to do, is switch between different themes using this method:

<script type="text/javascript">
      $(document).ready(function () {
          if($('body').hasClass('pink'))
          {
              $('head').append('<link rel="stylesheet" type="text/css" href="../css/mystylePink.css">');
          }
          else
          {
              $('head').append('<link rel="stylesheet" type="text/css" href="../css/mystyle.css">');
          }
      });
</script>

MY QUESTION: Apart form users not having javascript enabled, what complications/issues exists when loading a stylesheet like this? IE? Mobile browsers? Since I actually want to use this on a mobile site...

David Van Staden
  • 1,739
  • 9
  • 34
  • 52

2 Answers2

2

The main problem here would be the flash of unstyled content while the stylesheet loads, rather than IE or mobile browsers.

I suggest you use a CSS preprocessor (SASS, LESS) and just use one stylesheet with your normal styles and then override with the .pink class underneath.

.myClass{
  color: white;
  background: black;
}

.pink .myClass{
  color: pink;
  background: grey;
}
ahren
  • 16,803
  • 5
  • 50
  • 70
  • yeah I agree, thank you. Problem is that I have have many styles that do not use classes and uses element targeting: eg #wrapper ul li a{}, and I do not want to add styles to my existing html elements. So what I can do, is load a stylesheet to start of with, and then replace it with another one once the document is ready....Then of course there is preloading with window.onload - show a loading gif while everything is loading – David Van Staden Mar 25 '13 at 13:24
  • SASS/LESS will take care of specific element targeting. – ahren Mar 25 '13 at 13:25
  • ok cool, i see thank you...What about compatibility other than IE? Is it reliable and safe to use my method? – David Van Staden Mar 25 '13 at 13:26
1

This method isnt't working in IE8 and below.

You have to use another method, like IEss document.createStyleSheet() method.

See this discussion for more information: Can I load external stylesheets on request?

Community
  • 1
  • 1
Julian
  • 61
  • 4