是否可以在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”。
即使引用type="text/plain"
文件时用styles
指定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;
}