2

我想将外部 CSS 文件与正文中的 html 代码并排。

为什么?

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

我目前拥有的是:

<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 一起破解一些样式解析器,它至少将样式应用于基本定义。

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

任何提示都适用!

4

3 回答 3

4

您可以使用 CSS 的@import 规则

<style type="text/css">
  @import url("external.css");
</style> 
于 2012-08-04T16:34:59.177 回答
3

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

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

<body>
  ...
  <script type="text/javascript">
    $(document).ready(function() {
      $('head').append('<link rel="stylesheet" type="text/css" href="style.css">');
    });
  </script>
  ...
</body>
于 2012-08-04T20:02:55.990 回答
1

<link rel="stylesheet" type="text/css" href="style.css">-- 你也可以把它放在<body>标签里;它在 chrome 中工作得很好。

于 2012-08-04T16:53:33.363 回答