是否可以在html体中引用外部样式表?

时间:2012-08-04 16:32:14

标签: javascript html css

我希望将html代码并排放在外部CSS文件中。

为什么?

我正在开发一些包含在页面内的模板,但是从这些模板中我无法修改头部或者将JS / CSS引用添加到html head部分。

我目前拥有的是:

<html>
<head>
<!-- this i cannot edit -->
</head>
<body>
<!-- some html code -->
<!-- now comes what i can edit --> 
    <style>
    #mywidget {
     color: red;
    }
    </style>
    <div id="mywidget">
    hello
    </div>

<!-- end of section i can edit -->
<!-- other html code -->
</body>
</html>

我想把它变成像:

<html>
<head>
<!-- this i cannot edit -->
</head>
<body>
<!-- some html code -->
<!-- now comes what i can edit --> 

    <!-- LINK TO AN EXTERNAL CSS FILE -->

    <div id="mywidget">
    hello
    </div>

<!-- end of section i can edit -->
<!-- other html code -->
</body>
</html>

但我不希望每次加载页面时加载所有css的开销,所以我想把它放到外部文件中。

我想过使用javascript加载外部css(它将在同一个域中托管),然后创建一个元素并以某种方式插入内容......

我认为这应该有效,但是如果不是,我认为我可以使用jquery一起破解一些样式解析器,jquery至少应用于基本定义的样式。

但我相信一定有更好的方法!

任何暗示都是适当的!

3 个答案:

答案 0 :(得分:4)

您可以使用CSS的@import rule

<style type="text/css">
  @import url("external.css");
</style> 

答案 1 :(得分:3)

根据html标准将样式标签放入正文中确实无效(尽管它可能在某些浏览器中有效)

您可以将脚本放在正文中,然后您可以让脚本在您的脑海中插入样式链接。 jquery伪代码看起来像这样

<body>
  ...
  <script type="text/javascript">
    $(document).ready(function() {
      $('head').append('<link rel="stylesheet" type="text/css" href="style.css">');
    });
  </script>
  ...
</body>

答案 2 :(得分:1)

<link rel="stylesheet" type="text/css" href="style.css"> - 你也可以将它放在<body>标签中;它在铬合金中效果很好。

相关问题