63

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?

inavda
  • 333
  • 5
  • 15
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • 8
    GitHub is _not_ a CDN. If you're trying to use it as one, please don't. – Bojangles Dec 25 '12 at 19:15
  • `submime` text editor has awesome `Fetch` extension...pop URL in and will download any file or unpack a zip to local directory – charlietfl Dec 25 '12 at 20:38
  • 1
    possible duplicate of [Link and execute external JavaScript file hosted on GitHub](http://stackoverflow.com/questions/17341122/link-and-execute-external-javascript-file-hosted-on-github) – random Dec 02 '13 at 17:19

9 Answers9

53

https://rawgit.com has been shut down. This answer is unfortunately no longer relevant.


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.

Lix
  • 47,311
  • 12
  • 103
  • 131
  • @stu - 100% correct. I've added a note in my answer to mention it. – Lix Dec 25 '12 at 19:18
  • 2
    This should not work since GitHub changed the content type for raw.github.com See https://github.com/blog/1482-heads-up-nosniff-header-support-coming-to-chrome-and-firefox ... You can use www.rawgithub.com – klaustopher Dec 02 '13 at 13:51
  • It seems to be serving from raw.githubusercontent.com now – mork Jul 16 '15 at 09:30
  • 4
    Oct 8 2018 update from rawgit: "RawGit is now in a sunset phase and will soon shut down. It's been a fun five years, but all things must end." – Greg Sadetsky Oct 10 '18 at 20:15
  • 6
    "RawGit will soon shut down and is no longer serving new repos" – Tal Sep 11 '19 at 12:24
15

After enabling GitHub pages of your Repository, use following link:

<script src="https://[username].github.io/[repository]/[filename].js"></script>
Chintan Patel
  • 173
  • 1
  • 8
7

rawgit looks like shutting down by end of 2019,

some options for delivering content with with proper Content-Type headers.

  1. 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.
  2. jsdelivr =>for delivering javascript files
Shishir Arora
  • 5,521
  • 4
  • 30
  • 35
5

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

https://prnt.sc/obbrpn

https://prnt.sc/obbt69

https://prnt.sc/obbskb

bdalina
  • 503
  • 10
  • 16
4

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:

enter image description here

CoffeeCode
  • 4,296
  • 9
  • 40
  • 55
4

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.

Alex from Jitbit
  • 53,710
  • 19
  • 160
  • 149
1

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:

<script
  type="text/javascript"
  src="https://combinatronics.com/username/repo/master/src/file.js"
></script>
OfirD
  • 9,442
  • 5
  • 47
  • 90
0

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

0

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


Docs GitHub API get contents

Script and Example

I create a component that allows you drags the file to the input.

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

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/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>

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)
Carson
  • 6,105
  • 2
  • 37
  • 45