Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append Style Sheets in IE using jQuery?

Hello Guys,

I was just trying to create a plugin, and I needed it to be user-friendly so I want to append the <link/> tag on the head portion of the users page as my plugin is loaded. It works fine with all the other browsers (not sure of IE9, IE7 & IE6) but doesn't work for IE8! I don't what is getting wrong with my plugin, so I just created a sample page and faced the similar problem! Here is my test page HTML+jQuery Code ------

<html>
       <head>
              <script src="../jquery-1.6.min.js"></script>
              <script>
                       $(document).ready(function () {
                          $(document.head).append('<link rel="stylesheet" type="text/css" href="style.css" />');
                       });
              </script>
       </head>
       <body>
              <h1>Text!</h1>
       </body>
</html>

And here is my CSS code -----

body {
 background:#ddd; 
}
h1 {
 color: #789; 
}

So can anyone tell me where I'm going wrong or is this the problem of lifetime?

THANKS IN ADVANCE


After seeing the first comment and going to link supplied, I just created this sample code and found something amazing! See this ~~~

<html>
       <head>
              <script src="../jquery-1.6.min.js"></script>
              <script>
                       $(document).ready(function () {
                          if (document.getElementsByTagName('head')[0] === document.head) {
                           $("head").append('<link rel="stylesheet" type="text/css" href="style.css" />');
                          }else {
                           alert('This doesn\'t supports head appending!');
                          }
                       });
              </script>
       </head>
       <body>
              <h1>Text!</h1>
       </body>
</html>

On executing this page with my IE8 browser I get the message that

This doesn't supports head appending!

Well I don't what is wrong with my browser or is this the fault of IE8?


like image 569
Jack Billy Avatar asked May 21 '11 05:05

Jack Billy


1 Answers

if (document.createStyleSheet)
{
    document.createStyleSheet("style.css");
}
else
{
    $("head")
       .append('<link rel="stylesheet" type="text/css" href="style.css" />'); 
}
like image 68
Chris Fulstow Avatar answered Oct 12 '22 03:10

Chris Fulstow