Including JavaScript files from GitHub into HTML pages
JavascriptGithubJavascript Problem Overview
> #PAY ATTENTION! You can't include Github scripts directly from Github after this change.
>We added the X-Content-Type-Options: nosniff
header to our raw URL responses way back in 2011 as a first step in combating hotlinking. This has the effect of forcing the browser to treat content in accordance with the Content-Type
header. That means that when we set Content-Type: text/plain
for raw views of files, the browser will refuse to treat that file as JavaScript or CSS.
>But there are alternatives. **Check my answer to this question**.
I am trying to include a JavaScript file from GitHub into a local HTML file for testing (like an image found on the internet: <img src="http://...">
).
I would like something like this:
<script src="https://github.com/[username]/[repository]/blob/master/public/[fileName].js"></script>
The problem is that this doesn't work.
How can I do this?
Javascript Solutions
Solution 1 - Javascript
You will be able to do it with a URL similar to this:
https://rawgit.com/h5bp/html5-boilerplate/master/src/js/plugins.js
Note that this is not the same as clicking on the "raw" button within GitHub; that button will also give you a clean version of the file, but it will be sent with the wrong headers.
A Word of warning; the file is not not being served from GitHub. It is being
redirected through the rawgit.com
domain. As is stated on https://rawgit.com:
> Hey! rawgit.com is just for fun and is not associated with GitHub in any > way.
Keep in mind that the owner of that domain is now in control of the traffic and is able to manipulate it as they see fit.
Solution 2 - Javascript
After enabling GitHub pages of your Repository, use following link:
<script src="https://[username].github.io/[repository]/[filename].js"></script>
Solution 3 - Javascript
> rawgit looks like shutting down by end of 2019,
some options for delivering content with with proper Content-Type headers.
- https://raw.githack.com/ , https://combinatronics.com=>exact alternative but it cannot be used for fetching from client side javascript, as cors is enabled here.
- jsdelivr =>for delivering javascript files
Solution 4 - Javascript
You can include hosted CSS, HTML and JS file in GITHUB PAGES
Just click at the settings on your github repository then at this tab scroll down to the GitHub Pages and select with the dropdown
Then HOray you can now access it live
> This is the raw that returns text/plain mime type
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>
> And this is the live version
https://bdalina54.github.io/assets/js/terebra/acrior.js
<script src="https://bdalina54.github.io/assets/js/terebra/acrior.js"></script>
You can check my screenshot how I did it
Solution 5 - Javascript
This should work:
<script src="https://raw.github.com/[username]/[repository]/[branch]/[filename].js"></script>
Here is how you can get redirected to the needed address in github:
Solution 6 - Javascript
UPDATED ANSWER:
The old answer I gave in 2014 has stopped working, but you can use 3rd party CDN to serve js directly from github. Jsdelivr is one of those CDNs, powered by CloudFlare and Fastly.
Example:
<script src="https://cdn.jsdelivr.net/gh/<user>/<repo>/<filename>.js">
Or use their tool to convert: https://www.jsdelivr.com/github
OLD ANSWER:
This works even with github's recent change:
<script>
$.getScript("https://raw.github.com/username/repo/master/src/script.js");
</script>
PS. requires jQuery.
Solution 7 - Javascript
2021 Working Solution: Use Combinatorics.
See this answer for examples. Copying here a quick one:
> The only change is from raw.github.com
that becomes combinatronics.com
:
>
>
Solution 8 - Javascript
Try somethig like this:
<html>
<head>
<script src="https://raw.github.com/e0ne/BlogSamples/master/ModalDialog/AdvancedPopup/jquery.min.js"></script>
</head>
It's working for me
Solution 9 - Javascript
You can use the API provided by GitHub to get all the context, and then use a method similar to eval
to force write it in.
I don't recommend you use the way in any official product, but as a test or write some practice scripts, handy, can save a lot of duplication of code
- python solution
- javascript solution (see below script
GithubExplorer
)
Script and Example
I create a component that allows you drags the file to the input.
Below will show you how to load the content and embed it such that you can use it.
<link href="https://cdn.jsdelivr.net/npm/[email protected]/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>
below is a simple script that you know how to do after loading the content.
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)