簡體   English   中英

不使用 `.css` 擴展名引用外部 CSS 文件

[英]Reference an external CSS file without using the `.css` extension

是否可以在 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擴展名來緩解此問題,但對於此項目,我無法訪問后端服務器。

以下實現了您的意圖,但可以說是不好的做法。 它請求資源,然后將其插入style標簽,繞過瀏覽器的 MIME 檢查。 我建議獲取 CSS 並使用正確的Content-Type為其提供服務。

索引.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>

樣式.txt


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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM