簡體   English   中英

將 GitHub 中的 JavaScript 文件包含到 HTML 頁面中

[英]Including JavaScript files from GitHub into HTML pages

注意!

此更改后,您不能直接從 Github 包含 Github 腳本

我們早在 2011 年X-Content-Type-Options: nosniff標頭添加到我們的原始 URL 響應中,作為打擊盜鏈的第一步。 這具有強制瀏覽器根據Content-Type標頭處理內容的效果。 這意味着當我們為文件的原始視圖設置Content-Type: text/plain ,瀏覽器將拒絕將該文件視為 JavaScript 或 CSS。

但也有其他選擇。 檢查我對這個問題的回答


我正在嘗試將 GitHub 中的 JavaScript 文件包含到本地 HTML 文件中以進行測試(例如在 Internet 上找到的圖像: <img src="http://..."> )。

我想要這樣的東西:

<script src="https://github.com/[username]/[repository]/blob/master/public/[fileName].js"></script>

問題是這行不通。

我怎樣才能做到這一點?

您將能夠使用類似於以下內容的 URL 來執行此操作:

https://rawgit.com/h5bp/html5-boilerplate/master/src/js/plugins.js

請注意,這與單擊 GitHub 中的“原始”按鈕不同; 該按鈕還將為您提供文件的干凈版本,但它會以錯誤的標題發送。


一句警告; 該文件不是從 GitHub 提供的 它正在通過rawgit.com域重定向。 https://rawgit.com 所述

嘿! rawgit.com 只是為了好玩,與 GitHub 沒有任何關聯。

請記住,該域的所有者現在可以控制流量,並且能夠按照他們認為合適的方式操縱它。

啟用存儲庫的 GitHub 頁面后,使用以下鏈接:

<script src="https://[username].github.io/[repository]/[filename].js"></script>

rawgit 看起來像是在 2019 年底關閉,

使用適當的 Content-Type 標頭傳送內容的一些選項。

  1. https://raw.githack.com/ , https://combinatronics.com= >exact 替代但它不能用於從客戶端 javascript 獲取,因為這里啟用了 cors。
  2. jsdelivr => 用於傳遞 javascript 文件

您可以在GITHUB PAGES 中包含托管的CSSHTMLJS文件

只需單擊 github 存儲庫上的設置,然后在此選項卡上向下滾動到 GitHub 頁面並使用下拉菜單進行選擇

然后 HOray 您現在可以實時訪問它

這是返回 text/plain mime 類型的原始數據

https://raw.githubusercontent.com/bdalina54/bdalina54.github.io/master/assets/js/terebra/acrior.js

<script src="https://raw.githubusercontent.com/bdalina54/bdalina54.github.io/master/assets/js/terebra/acrior.js"></script>

這是現場版

https://bdalina54.github.io/assets/js/terebra/acrior.js

<script src="https://bdalina54.github.io/assets/js/terebra/acrior.js"></script>

你可以查看我的截圖我是怎么做的

https://prnt.sc/obbrpn

https://prnt.sc/obbt69

https://prnt.sc/obbskb

這應該有效:

<script src="https://raw.github.com/[username]/[repository]/[branch]/[filename].js"></script>

以下是重定向到 github 中所需地址的方法:

在此處輸入圖片說明

更新的答案:

我在 2014 年給出的舊答案已經停止工作,但您可以使用 3rd 方 CDN 直接從 github 服務 js。 Jsdelivr 是這些 CDN 之一,由 CloudFlare 和 Fastly 提供支持。

例子:

<script src="https://cdn.jsdelivr.net/gh/<user>/<repo>/<filename>.js">

或者使用他們的工具進行轉換: https : //www.jsdelivr.com/github

舊答案:

這甚至適用於 github 最近的更改:

<script>
  $.getScript("https://raw.github.com/username/repo/master/src/script.js");
</script>

附注。 需要jQuery。

嘗試這樣的事情:

<html>
<head>
    <script src="https://raw.github.com/e0ne/BlogSamples/master/ModalDialog/AdvancedPopup/jquery.min.js"></script>
</head>

它對我有用

可以使用GitHub提供API獲取所有上下文,然后使用類似於eval的方法強制寫入。

我不建議你在任何官方產品中使用這種方式,但是作為測試或者寫一些練習腳本,好用,可以省去很多重復的代碼


Docs GitHub API 獲取內容

腳本和示例

我創建了一個組件,允許您將文件拖到輸入中。

https://api.github.com/repos/ CarsonSlovoka / excel /contents/ app/urls/static/js/pkg/input/ask- file.js ?ref= d625296

下面將向您展示如何加載內容並將其嵌入以便您可以使用它。

 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer"/> <!-- 👆 Above CSS are not must be given, I want it more pretty, that all. --> <input data-com="ask-file" placeholder="select or drag the file to attach" multiple> <script type="module"> function GithubExplorer() { /** * @param {string} owner Username * @param {string} repo repository name * @param {string} path filepath * @param {string} branch branch name or SHA1 * @param {string} token The token is used for project private. generate new token 👉 https://github.com/settings/tokens * */ this.Query = async (owner, repo, path, {branch = "master", token = undefined}) => { // https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options const url = `https://api.github.com/repos/${owner}/${repo}/contents/${path}?ref=${branch}` const headers = { accept: "application/vnd.github.v3.raw", } if (token) { headers["authorization"] = `token ${token}` } const response = await fetch(url, { method: 'GET', headers, }) if (!response.ok) { const errMsg = await response.text() throw Error(`${response.statusText} (${response.status}) | ${errMsg} `) } return await response.blob() } } (async () => { const github = new GithubExplorer() const blobAskFileScript = await github.Query("CarsonSlovoka", "excel", "app/urls/static/js/pkg/input/ask-file.js", {branch: "d625296"}) let askFileScriptText = await blobAskFileScript.text() askFileScriptText = askFileScriptText.replaceAll("export class AskInputFile", "class AskInputFile") document.querySelector(`head`).append( document.createRange().createContextualFragment(` <script>${askFileScriptText}<\\/script>`) ) AskInputFile.BuildAll() // This function is from the script. })() </script>


下面是一個簡單的腳本,您知道在加載內容后該怎么做。

 const body = document.querySelector(`body`) const range = document.createRange() const content = `<script>console.log("hello world")<\\/script>` const frag = range.createContextualFragment(content) body.append(frag)

2021 工作解決方案:使用組合數學

有關示例,請參閱此答案 在這里復制一個快速的:

唯一的變化是從raw.github.com變成了combinatronics.com

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM