在不使用 `.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
,我会在浏览器的终端中收到以下错误:
The stylesheet https://example.com/styles was not loaded because its MIME type, “text/plain”, is not “text/css”.
即使我在引用 styles
文件时用 type="text/plain"
指定 MIME 类型,我仍然会得到同样的错误。
同样,我无法控制 styles
文件的名称或扩展名。我只知道它是 URL。显然,这个问题可以通过让 Web 服务器下载 styles
文件然后为本地副本提供 .css
扩展名来缓解,但对于这个项目,我无法访问后端服务器。
以下实现了您的意图,但可以说是不好的做法。它请求资源,然后将其插入 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;
}
是否可以在 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
,我会在浏览器的终端中收到以下错误:
The stylesheet https://example.com/styles was not loaded because its MIME type, “text/plain”, is not “text/css”.
即使我在引用 styles
文件时用 type="text/plain"
指定 MIME 类型,我仍然会得到同样的错误。
同样,我无法控制 styles
文件的名称或扩展名。我只知道它是 URL。显然,这个问题可以通过让 Web 服务器下载 styles
文件然后为本地副本提供 .css
扩展名来缓解,但对于这个项目,我无法访问后端服务器。
以下实现了您的意图,但可以说是不好的做法。它请求资源,然后将其插入 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;
}