外部 CSS 下载到 chrome 但未反映

External CSS downloaded in chrome but not reflected

我有一个外部 CSS 样式,它已在 chrome 中下载但未反映出来。当我手动更改 stylesheet inline 时,它​​会反映出来。它在 Firefox 浏览器中工作正常。

加载了以下格式的样式 sheet:

if (domainURL != '') {
    link = document.createElement('LINK');
    link.rel = 'stylesheet';
    link.href = domainURL;
    link.type = 'text/css';
    document.head.appendChild(link);
}

我也尝试了以下解决方案,但 none 有效。

  1. 刷新
  2. 正在清除缓存
  3. 以 link 样式添加版本(例如:https://tel.org.css?v=1.111

请有人帮我解决这个 chrome 浏览器问题。

到目前为止,我的猜测是 CSS 文件没有被应用,因为它有一个错误的 HTTP header content-type whose value should be a mime-type 和一个编码参数 (text/css; charset: UTF-8),而是一个未知的值 (css).

似乎 Firefox 覆盖了错误的 content-type header 并嗅探(猜测)信息(因为没有 x-content-type-options: nosniff 它是允许的)。而 Chrome 可能反而尊重 header “如果它在那里,那一定是有原因的”,因此不知道如何处理未知类型的文件。

要测试此诊断,您应该尝试:

  • 加载另一个 CSS 文件(如果可能的话托管在其他地方,因为它可能是服务器设置错误 header)。不一定要漂亮,看是否适用即可。
  • 如果可以,请更改 header。修复 content-type 或删除它(并让浏览器嗅探 mime-type,这对安全性来说不是理想的选择,但会起作用)。
  • 在 JS 中创建样式表:
    fetch('your-css-file.css')
        .then(response => response.text())
        .then(styleString => {
            const style = document.createElement('style')
            style.textContent = styleString
            document.head.append(style)
        })
    

我自己测试了第三个解决方案(在 JS 中获取并创建一个带有文本响应的样式表)并且它有效。但是,由于以下规则,它会尝试下载图像:

.logo { 
  background-image:  url(../logo/images6.1624696593222.jpg);

而且,和以前一样,我错了content-type header:

Request URL: https://greatone11.aroscop.org/logo/images6.1624696593222.jpg
content-type: text/html; charset=UTF-8
server: nginx/1.18.0
x-powered-by: Express

您似乎已将 expressjs as your server and nginx 作为您的反向代理。其中之一就是搞乱你的 headers。我的赌注是 Express,因为它可能是为 angular 设置的,而你正试图在此处做一些 not-very-angular-things!