【问题标题】:Reference an external CSS file without using the `.css` extension引用外部 CSS 文件而不使用 `.css` 扩展名
【发布时间】:2020-05-14 11:18:03
【问题描述】:

是否可以在 HTML 中将纯文本文件作为 CSS 文件引用?我无法控制外部 CSS 文件的名称或扩展名。以以下为例:

我有一个名为index.html 的文件,在<head> 标签之间有以下代码:

<head>
    <title>Website</title>
    <link rel="stylesheet" href="https://example.com/styles">
</head>

example.com/styles 的外部文件如下所示:

body {
    color: red;
    font-family: sans-serif;
    background: blue;
}

如果我打开 index.html 我在浏览器的终端中收到以下错误:

样式表 https://example.com/styles 未加载,因为它的 MIME 类型“text/plain”不是“text/css”。

即使我在引用 styles 文件时使用 type="text/plain" 指定 MIME 类型,我仍然会收到相同的错误。

同样,我无法控制 styles 文件的名称或扩展名。我只知道它的网址。显然,可以通过让 Web 服务器下载 styles 文件然后给本地副本添加 .css 扩展名来缓解这个问题,但是对于这个项目,我无法访问后端服务器。

【问题讨论】:

  • 唯一想到的是服务器上有一些魔法可以将该路径插入到 CSS 文件中,但我只是问为什么这对你来说是这样的?
  • 我在玩IPFS,其中文件由它们的内容哈希而不是它们的地址提供服务。因此,如果我将style.css 上传到 IPFS,我就可以使用其内容的哈希值来引用该文件。 IPFS 从文件名中去除 .css 或任何其他扩展名。

标签: html css mime-types


【解决方案1】:

以下实现了您的意图,但可以说是不好的做法。它请求资源,然后将其插入到style 标记中,绕过浏览器的 MIME 检查。我建议获取 CSS 并使用正确的 Content-Type 提供它。

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>CSS From Text File</title>
  <style id="style"></style>
</head>

<body>
  <div id="styled"></div>
</body>

<script>
  const style = document.getElementById('style');
  const req = new XMLHttpRequest();
  req.onloadend = () => {
    style.innerHTML = req.responseText;
  };
  req.open("GET", "style.txt");
  req.send();
</script>

</html>

style.txt


#styled {
  height: 100px;
  width: 100px;
  background: red;
}

【讨论】:

  • 这是一个创造性的解决方法,它在一定程度上解决了这个问题。然而,使用这种方法的网站显然仍然有点粗略,因为它们绕过了 MIME 检查,正如你提到的。我想另一种解决方案是引入样式并直接从index.html 之间的&lt;style&gt; 标签提供它们,就像你的JS 所做的那样。
  • 我同意! @reelyard
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-04
  • 2018-05-02
  • 2016-07-22
相关资源
最近更新 更多