【问题标题】:How can I use github to host an external CSS file?如何使用 github 托管外部 CSS 文件?
【发布时间】:2020-08-27 17:05:49
【问题描述】:

我将我的 css 上传到 github,然后转到网站上的文件并单击 raw 选项。我尝试将其添加到网页,但 chrome 出现以下错误:

资源解释为样式表,但使用 MIME 类型 text/plain 传输: “https://raw.githubusercontent.com/me/my-repo/master/style.css”。

跨域读取阻塞 (CORB) 阻止了 MIME 类型为 text/plain 的跨域响应 https://raw.githubusercontent.com/me/my-repo/master/style.css。详情请见https://www.chromestatus.com/feature/5629709824032768

如何才能成功添加此 CSS?我也在用 javascript 添加它:

var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
link.setAttribute('href', 'https://raw.githubusercontent.com/me/my-repo/master/style.css');
document.getElementsByTagName('head')[0].appendChild(link);

【问题讨论】:

标签: javascript css git google-chrome github


【解决方案1】:

您可以在 Github Pages 上托管您的文件,只需转到 repo 设置[1],找到“Github Pages”部分并设置您的分支[2],然后单击“保存”。你会看到信息[3]。然后你去https://YOUR-GITHUB-USERNAME/REPO-NAME(如果你有index.html或任何文件,例如/src/css/style.css)你可以在任何网站上加载CSS、JS或其他文件

<link rel="stylesheet" href="path/to/file/style.min.css">

[1]:


[2]:


[3]:

【讨论】:

    【解决方案2】:

    也许这有点复杂,因为您必须通过 Javascript 获取文件,然后将其打印到样式标签中。 CORB 与服务器配置有关,而不是客户端。

    JS 示例:

    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", "https://raw.githubusercontent.com/me/my-repo/master/style.css", true);
    xhttp.onreadystatechange = function() {
      if (xhttp.readyState === 4) {
        if (xhttp.status === 200) {
          var link = document.createElement('style');
    link.innerHTML=xhttp.responseText;
    document.getElementsByTagName('head')[0].appendChild(link);
        }
      }
    }
    xhttp.send(null);
    

    【讨论】:

      【解决方案3】:

      Lawl,您输入了与您的个人帐户相关联的链接,此链接不公开。 (尝试将您的链接放入浏览器。确保将您的项目配置为公开。

      还请务必查看此类似帖子: How to link my CSS to my HTML in a github hosted site

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-24
        • 2017-02-03
        • 1970-01-01
        • 2011-04-07
        • 2021-12-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多