链接并执行托管在 GitHub 上的外部 JavaScript 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17341122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:57:21  来源:igfitidea点击:

Link and execute external JavaScript file hosted on GitHub

javascriptgithub

提问by AuthorProxy

When I try to change the linked reference of a local JavaScript file to a GitHub raw version my test file stops working. The error is:

当我尝试将本地 JavaScript 文件的链接引用更改为 GitHub 原始版本时,我的测试文件停止工作。错误是:

Refused to execute script from ... because its MIME type (text/plain) is not executable, and strict MIME type checking is enabled.

拒绝从 ... 执行脚本,因为其 MIME 类型 ( text/plain) 不可执行,并且启用了严格的 MIME 类型检查。

Is there a way to disable this behavior or is there a service that allows linking to GitHub raw files?

有没有办法禁用这种行为,或者是否有允许链接到 GitHub 原始文件的服务?

Working code:

工作代码:

<script src="bootstrap-wysiwyg.js"></script>

Non-working code:

非工作代码:

<script src="https://raw.github.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js"></script>

回答by Troy Alford

There isa good workaround for this, now, by using jsdelivr.net.

这里一个很好的办法解决这一点,现在,通过使用jsdelivr.net

Steps:

步骤

  1. Find your link on GitHub, and click to the "Raw" version.
  2. Copy the URL.
  3. Change raw.githubusercontent.comto cdn.jsdelivr.net
  4. Insert /gh/before your username.
  5. Remove the branchname.
  6. (Optional) Insert the versionyou want to link to, as @version(if you do not do this, you will get the latest- which may cause long-term caching)
  1. 在 GitHub 上找到您的链接,然后单击“原始”版本。
  2. 复制网址。
  3. 更改raw.githubusercontent.comcdn.jsdelivr.net
  4. /gh/在您的用户名前插入。
  5. 删除branch名称。
  6. (可选)插入您要链接的版本,因为@version(如果不这样做,您将获得最新的- 这可能会导致长期缓存)


Examples:

例子

http://raw.githubusercontent.com/<username>/<repo>/<branch>/path/to/file.js

Use this URL to get the latest version:

使用此 URL 获取最新版本:

http://cdn.jsdelivr.net/gh/<username>/<repo>/path/to/file.js

Use this URL to get a specific version or commit hash:

使用此 URL 获取特定版本或提交哈希:

http://cdn.jsdelivr.net/gh/<username>/<repo>@<version or hash>/path/to/file.js

For production environments, consider targeting a specific tag or commit-hash rather than the branch. Using the latestlink may result in long-term caching of the file, causing your link to not be updated as you push new versions. Linking to a file by commit-hash or tag makes the link unique to version.

对于生产环境,请考虑针对特定标签或提交哈希而不是分支。使用最新的链接可能会导致文件长期缓存,导致您的链接在您推送新版本时没有更新。通过提交哈希或标签链接到文件使链接对于版本是唯一的。



Why is this needed?

为什么需要这个?

In 2013, GitHub started using X-Content-Type-Options: nosniff, which instructs more modern browsers to enforce strict MIME type checking. It then returns the raw files in a MIME type returned by the server, preventing the browser from using the file as-intended (if the browser honors the setting).

2013 年,GitHub 开始使用X-Content-Type-Options: nosniff,它指示更现代的浏览器强制执行严格的 MIME 类型检查。然后它以服务器返回的 MIME 类型返回原始文件,防止浏览器按预期使用该文件(如果浏览器接受该设置)。

For background on this topic, please refer to this discussion thread.

有关此主题的背景信息,请参阅此讨论主题

回答by Peeja

This is no longer possible. GitHub has explicitly disabled JavaScript hotlinking, and newer versions of browsers respect that setting.

这已经不可能了。GitHub 已明确禁用 JavaScript 热链接,并且较新版本的浏览器尊重该设置。

Heads up: nosniff header support coming to Chrome and Firefox

注意:Chrome 和 Firefox 将支持 nosniff 标头

回答by Paul Browne

rawgithub.comredirects to rawgit.comSo the above example would now be

rawgithub.com重定向到rawgit.com所以上面的例子现在是

http://rawgit.com/user/package/master/link.min.js

http://rawgit.com/user/package/master/link.min.js

回答by chharvey

GitHub Pagesis GitHub's official solution to this problem.

GitHub Pages是 GitHub 官方针对这个问题的解决方案。

raw.githubusercontentmakes all files use the text/plainMIME type, even if the file is a CSS or JavaScript file. So going to https://raw.githubusercontent.com/?user?/?repo?/?branch?/?filepath?will not be the correct MIME type but instead a plaintext file, and linking it via <link href="..."/>or <script src="..."></script>won't work—the CSS won't apply / the JS won't run.

raw.githubusercontent使所有文件都使用text/plainMIME 类型,即使文件是 CSS 或 JavaScript 文件。因此,https://raw.githubusercontent.com/?user?/?repo?/?branch?/?filepath?将不会是正确的 MIME 类型,而是纯文本文件,并且通过<link href="..."/><script src="..."></script>将不起作用 - CSS 将不适用 / JS 将无法运行。

GitHub Pageshosts your repo at a special URL, so all you have to do is check-in your files and push. Note that in most cases, GitHub Pages requires you to commit to a special branch, gh-pages.

GitHub Pages在一个特殊的 URL托管你的存储库,所以你所要做的就是签入你的文件并推送。请注意,在大多数情况下,GitHub Pages 要求您提交到一个特殊的分支gh-pages.

On your new site, which is usually https://?user?.github.io/?repo?, every file committed to the gh-pagesbranch (the most recent commit) is present at this url. So then you can link to your js file via <script src="https://?user?.github.io/?repo?/file.js"></script>, and this will be the correct MIME type.

在您的新站点(通常是 )上https://?user?.github.io/?repo?,提交到gh-pages分支的每个文件(最近的提交)都出现在此 url 中。因此,您可以通过 链接到您的 js 文件<script src="https://?user?.github.io/?repo?/file.js"></script>,这将是正确的 MIME 类型。

Do you have build files?

你有构建文件吗?

Personally, my recommendation is to run this branch parallel to master. On the gh-pagesbranch, you can edit your .gitignorefile to check inall the dist/build files you need for your site (e.g. if you have any minified/compiled files), while keeping them ignoredon your masterbranch. This is useful because you typically don't want to track changes in build files in your regular repo. Every time you want to update your hosted files, simply merge masterinto gh-pages, rebuild, commit, and then push.

就个人而言,我的建议是将此分支与master. 在gh-pages分支上,您可以编辑.gitignore文件以签入站点所需的所有 dist/build 文件(例如,如果您有任何缩小/编译的文件),同时在您的分支上忽略它们master。这很有用,因为您通常不想跟踪常规存储库中构建文件的更改。每次要更新托管文件时,只需合并mastergh-pages、重建、提交,然后推送即可。

(protip: you can merge and rebuild in the same commit with these steps:)

(提示:您可以通过以下步骤在同一提交中合并和重建:)

$ git checkout gh-pages
$ git merge --no-ff --no-commit master  # prepare the merge but don't commit it (as if there were a merge conflict)
$ npm run build                         # (or whatever your build process is)
$ git add .                             # stage the newly built files
$ git merge --continue                  # commit the merge
$ git push origin gh-pages

回答by yurenchen

https://raw.githack.com/

https://raw.githack.com/

found this site supply a CDN for

发现这个站点提供了一个 CDN

  • remove nosniffhttp header
  • fix mime typeby ext name
  • 删除nosniffhttp头
  • mime type按分机名称修复

and this site:

和这个网站:

https://rawgit.com/

https://rawgit.com/

NOTE: RawGit has reached the end of its useful life

注意:RawGit 已达到其使用寿命

回答by sachinjain024

Above answers clearly answer the question but I want to provide another alternative - A different view/approach to solve the similar problem.

以上答案清楚地回答了这个问题,但我想提供另一种选择 - 解决类似问题的不同观点/方法。

You can also use browser extension to remove X-Content-Type-Optionsresponse header for raw.githubusercontent.comfiles. There are couple of browser extensions to modify response headers.

您还可以使用浏览器扩展删除文件的X-Content-Type-Options响应头raw.githubusercontent.com。有几个浏览器扩展可以修改响应头。

  1. Requestly: Chrome + Firefox
  2. Modify Headers: Firefox
  1. 请求:Chrome + Firefox
  2. 修改标题:Firefox

If you use Requestly, I can suggest two solutions

如果您使用Requestly,我可以建议两种解决方案

Solution 1: Use Modify Headers Rule and remove the response header

解决方案 1:使用 Modify Headers Rule 并删除响应标头

Steps

脚步

  1. Install Requestly from http://www.requestly.in
  2. Go to Rules Page
  3. Click on Add Icon to create a rule
  4. Select Modify Headers
  5. Give a Name and Descripton
  6. Select Remove-> Response-> X-Content-Type-Options
  7. In Source field, enter Url-> Contains-> raw.githubusercontent.com
  1. http://www.requestly.in安装 Requestly
  2. 进入规则页面
  3. 单击添加图标以创建规则
  4. 选择修改标题
  5. 给出名称和描述
  6. 选择Remove-> Response->X-Content-Type-Options
  7. 在源字段中,输入Url-> Contains->raw.githubusercontent.com

Solution 2: Use Replace host Rule

解决方案 2:使用替换主机规则

  1. Install Requestly from http://www.requestly.in
  2. Go to Rules Page
  3. Click on Add Icon to create a rule
  4. Replace raw.githubusercontent.comwith rawgit.com
  1. http://www.requestly.in安装 Requestly
  2. 进入规则页面
  3. 单击添加图标以创建规则
  4. 替换raw.githubusercontent.comrawgit.com

Check this screenshot for more detailsenter image description here

查看此屏幕截图了解更多详情在此处输入图片说明

How to test

如何测试

We created a simple JS Fiddle to test out if we can use raw github files as scripts in our code. Here is the Fiddlewith the following code

我们创建了一个简单的 JS Fiddle 来测试我们是否可以在我们的代码中使用原始 github 文件作为脚本。这是 带有以下代码的小提琴

<center id="msg"></center>

<script src="https://raw.githubusercontent.com/sachinjain024/practicebook/master/web-extensions-master/storage/background.js"></script>
<script>
try {
  if (typeof BG.Methods !== 'undefoned') {
    document.getElementById('msg').innerHTML = 'Script evaluated successfully!';
  }
} catch (e) {
  document.getElementById('msg').innerHTML = 'Problem evaluating script';
}
</script>

If you see Script evaluated successfully!, It means you are able to use raw github file in your code Otherwise Problem evaluating scriptindicates that there is some problem while executing script from raw github source.

如果您看到Script evaluated successfully!,则表示您可以在代码中使用原始 github 文件,否则Problem evaluating script表示从原始 github 源执行脚本时存在一些问题。

I also wrote an articleon Requestly blogabout this. Please refer it for more details.

我还在Requestly 博客上写了一篇关于此的文章。详情请参阅。

Hope it helps!!

希望能帮助到你!!

Disclaimer: I am author of RequestlySo you can blame for anything you don't like.

免责声明:我是Requestly 的作者所以你可以责怪任何你不喜欢的东西。

回答by Tomer Ben David

To make things clear and short

使事情清楚和简短

//raw.githubusercontent.com--> //rawgit.com

//raw.githubusercontent.com--> //rawgit.com

Note that this is handled by rawgit's development hosting and not their cdn for production hosting

请注意,这是由 rawgit 的开发托管处理的,而不是他们用于生产托管的 CDN

回答by Daniel Sokolowski

My use case was to load 'bookmarklets' direclty from my Bitbucket account which has same restrictions as Github. The work around I came up with was to AJAX for the script and run evalon the response string, below snippet is based on that approach.

我的用例是从我的 Bitbucket 帐户直接加载“书签”,该帐户与 Github 具有相同的限制。我想出的解决方法是将 AJAX 用于脚本并eval在响应字符串上运行,下面的代码片段基于该方法。

<script>
    var sScriptURL ='<script-URL-here>'; 
    var oReq = new XMLHttpRequest(); 
    oReq.addEventListener("load", 
       function fLoad() {eval(this.responseText + '\r\n//# sourceURL=' + sScriptURL)}); 
    oReq.open("GET", sScriptURL); oReq.send(); false;
</script>

Note that appending of sourceURLcomment is to allow for debuging of the script within browser's developer tools.

请注意,附加sourceURL注释是为了允许在浏览器的开发人员工具中调试脚本。

回答by Fahim Raza

When a file is uploaded to github you can use it as external source or free hosting. Troy Alford has explained it well above. But to make it easier let me tell you some easy steps then you can use a github raw file in your site:

当文件上传到 github 时,您可以将其用作外部源或免费托管。特洛伊·奥尔福德(Troy Alford)在上面已经很好地解释了这一点。但是为了方便起见,让我告诉您一些简单的步骤,然后您可以在您的站点中使用 github 原始文件:

Here is your file's link:

这是您文件的链接:

https://raw.githubusercontent.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js

https://raw.githubusercontent.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js

Now to execute it you have to remove https://and the dot( . ) between rawand githubusercontent

现在要执行它,您必须删除https://rawgithubusercontent之间的点( . )

Like this:

像这样:

rawgithubusercontent.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js

rawgithubusercontent.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js

Now when you will visit this link you will get a link that can be used to call your javascript:

现在,当您访问此链接时,您将获得一个可用于调用 javascript 的链接:

Here is the final link:

这是最终链接:

https://rawgit.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js

https://rawgit.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js

Similarly if you host a css file you have to do it as mentioned above. It is the easiest way to get simple link to call your external css or javascript file hosted on github.

同样,如果您托管一个 css 文件,则必须按上述方式进行。这是获取简单链接以调用托管在 github 上的外部 css 或 javascript 文件的最简单方法。

I hope this is helpful.

我希望这是有帮助的。

Referance URL: http://101helper.blogspot.com/2015/11/store-blogger-codes-on-github-boost-blogger-speed.html

参考网址:http://101helper.blogspot.com/2015/11/store-blogger-codes-on-github-boost-blogger-speed.html

回答by santosh

I found the error was shown due to the comments at the beginning of file , You can solve this issue , by simply creating your own file without comment and push to git, it shows no error

我发现错误是由于文件开头的注释而显示的,您可以解决这个问题,只需创建自己的不带注释的文件并推送到 git,它就不会显示任何错误

For proof you can try these two file with same code of easy pagination :

为了证明,您可以使用相同的简单分页代码尝试这两个文件:

without comment

不加评论

with comment

有评论