开发者

How to append Style Sheets in IE using jQuery?

开发者 https://www.devze.com 2023-03-07 16:27 出处:网络
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

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>
           开发者_Go百科   <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?



if (document.createStyleSheet)
{
    document.createStyleSheet("style.css");
}
else
{
    $("head")
       .append('<link rel="stylesheet" type="text/css" href="style.css" />'); 
}


You're using document.head to access the head. document.head is only a recent addition to the DOM, as part of HTML5. So, it's not universally supported.

If you want to use it, you should add a shim before calling it:

document.head = document.head || document.getElementsByTagName('head')[0];

Otherwise, you can just append directly to the <head> tag (which is recommended, since that's half the point of using jQuery's syntactic sugar):

$("head").append(...);
0

精彩评论

暂无评论...
验证码 换一张
取 消