是否可以在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;
}