最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to load stylesheets after loading and displaying page without any style - Stack Overflow

programmeradmin1浏览0评论

I was thinking instead of loading everything in parallel. I will allow to load and display the basic no-styled layout and then will load the css file after page has finished loading, but being a newbie in Javascript. I am not able to do this.

Till now I have tryed:

<head>
   <script type='text/javascript'>
      function addstyle()
      {
        document.getElementBytype('text/css').href='style.css';
      }
   </script>
   <link rel="stylesheet" type="text/css" href="">
</head>
<body onload="addstyle()">
   <h1>Good Morning</h1>
   <p>Hello whats up</p>
   <p>Hope you will have a great day ahead</p>
</body>

Here as you can see, I am trying to load style.css after the page is displayed in the browser, but it is not working.

I was thinking instead of loading everything in parallel. I will allow to load and display the basic no-styled layout and then will load the css file after page has finished loading, but being a newbie in Javascript. I am not able to do this.

Till now I have tryed:

<head>
   <script type='text/javascript'>
      function addstyle()
      {
        document.getElementBytype('text/css').href='style.css';
      }
   </script>
   <link rel="stylesheet" type="text/css" href="">
</head>
<body onload="addstyle()">
   <h1>Good Morning</h1>
   <p>Hello whats up</p>
   <p>Hope you will have a great day ahead</p>
</body>

Here as you can see, I am trying to load style.css after the page is displayed in the browser, but it is not working.

Share Improve this question edited Jan 14, 2014 at 11:19 Hüseyin BABAL 15.6k5 gold badges52 silver badges74 bronze badges asked Jan 14, 2014 at 11:17 user2930650user2930650
Add a ment  | 

2 Answers 2

Reset to default 7

Try this:

<head>
    <script type='text/javascript'>
        function addstyle()
        {
            document.getElementById('style').href='style.css';
        }
    </script>
    <link rel="stylesheet" id="style" type="text/css" href="">
</head>
<body onload="addstyle()">
    <h1>Good Morning</h1>
    <p>Hello whats up</p>
    <p>Hope you will have a great day ahead</p>
</body>

If you are using jQuery you can do something like this:

$(document).ready(function(){
    var $style_element = $(document.createElement('style'));
    $style_element.attr({href:'http://netdna.bootstrapcdn./bootstrap/3.0.3/css/bootstrap.min.css', rel:'stylesheet', type:'text/css', id:'some_id'});
    $('head').append($style_element);
});
发布评论

评论列表(0)

  1. 暂无评论