热链接资源,如直接从GitHub的JavaScript文件

Hotlink resources like JavaScript files directly from GitHub

本文关键字:GitHub JavaScript 文件 链接 资源      更新时间:2023-12-28

我问了一个关于包含GitHub资源的问题,答案是使用原始链接:

https://raw.github.com/username/repository/branch/file.js

我正在尝试包括一个脚本使用:

<script
   type="text/javascript"
   src="https://raw.github.com/username/repo/master/src/file.js"
></script>

但我得到以下错误:

拒绝执行来自"的脚本https://raw.github.com/username/repo/master/src/file.js',因为它的MIME类型('text/plain')是不可执行的,并且启用了严格的MIME类型检查。

有什么替代方案可以修复这个错误吗?

用法示例

我在生产中不使用这个,但用于演示页面:

project-repository-from-github
  ├─ master
  │   ├─ src
  │   │   └─ my-jQuery-plugin.js
  │   └─ README.md
  └─ gh-pages
      ├─ css
      │   └─ style.css
      └─ index.html

在index.html页面中,我想要my-jQuery-plugin.js的最新版本。因此,我会在脚本中包含原始URL。

如何修复错误?

是的,Github在2013年4月改变了这一点:

早在2011年,我们就在原始URL响应中添加了X-Content-Type-Options: nosniff标头,作为对抗热链接的第一步。这具有强制浏览器根据Content-Type报头来处理内容的效果。这意味着,当我们为文件的原始视图设置Content-Type: text/plain时,浏览器将拒绝将该文件视为JavaScript或CSS。

但多亏了http://combinatronics.com/我们可以包括GH脚本。唯一的变化是从raw.github.com变成combinatronics.com:

<script
   type="text/javascript"
   src="https://combinatronics.com/username/repo/master/src/file.js"
></script>

该项目托管在开源的Github上。

是的,@Lix是正确的。这些文件不是由Github提供的,而是由combintronics提供的。


我发现的另一个变通方法是:

<script
   type="text/javascript"
   src="https://combinatronics.com/username/repo/master/src/file.js"
></script>

您可以使用$.getScriptjQuery函数:

<script>
  $.getScript("https://combinatronics.com/username/repo/master/src/file.js", function () {
    /* do something when loaded */
  });
</script>

我发现对我来说最好的解决方案是使用GitHub页面:https://pages.github.com/

限制是,您只能使用repo中的一个分支来保存脚本(即:gh pages分支)

示例用法
将test.js脚本推送到REPO的gh页面分支。

脚本在您的用户名.github.io/REPO/test.js上(更新可能需要大约10分钟)

其他解决方案
http://rawgithub.com如果你不更改脚本(CDN永远缓存一个特定的url),这对开发和生产(使用CDN)都有好处。