Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Stylesheet with jQuery

Tags:

jquery

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

like image 337
David Van Staden Avatar asked May 21 '26 22:05

David Van Staden


2 Answers

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;
}
like image 116
ahren Avatar answered May 23 '26 12:05

ahren


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?

like image 44
Julian Avatar answered May 23 '26 11:05

Julian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!