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...

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

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
SASS/LESS will take care of specific element targeting.
ok cool, i see thank you...What about compatibility other than IE? Is it reliable and safe to use my method?
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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.