anjanesh
anjanesh

Reputation: 4251

How to link files directly from Github (raw.github.com)

Are we allowed to link files directly from Github ?

<link rel="stylesheet" href="https://raw.github.com/username/project/master/style.css"/>
<script src="https://raw.github.com/username/project/master/script.js"></script>

I know this is allowed on Google Code. This way I don't have to worry about updating a local file.

Upvotes: 121

Views: 183451

Answers (11)

P&#233;ter Szilv&#225;si
P&#233;ter Szilv&#225;si

Reputation: 2079

RawGit was a popular service for serving raw files directly from GitHub repositories. However, as multiple comments are mentioning, it has reached the end of its lifetime.

There are alternative options for serving raw files from GitHub repositories.

GitHub Raw Content URL

You can directly use GitHub's raw content URL to serve files. For example:

https://github.com/username/repository/raw/main/path/to/file.ext

As shown in the example, you can replace blob with raw in the file URL to get the raw content link.

GitHub Pages

GitHub Pages is a way to host static websites and assets, including images, directly from your GitHub repository. You can create a gh-pages branch or use the docs folder in your main branch to host your assets.

Showcase example

Here is an example of linking a PNG file from GitHub. There is an image under my repository:

https://github.com/SzilvasiPeter/azure-container-deployment/blob/main/architecture_diagram.png

First, we must adapt the URL by replacing the blob with raw. In my case, the URL becomes this:

https://github.com/SzilvasiPeter/azure-container-deployment/raw/main/architecture_diagram.png

Finally, I can link this image from an index.html page:

<html>
  <head>
    <title>My Website</title>
  </head>
  <body>
    <h1>Welcome To My Website!</h1>
    <img src="https://github.com/SzilvasiPeter/azure-container-deployment/raw/main/architecture_diagram.png" alt="Picture from Github">
  </body>
</html>

When I open the index.html, I get the following view.

enter image description here

Upvotes: 0

Jens
Jens

Reputation: 9130

Previous answers suggested to use raw.github.com or rawgithub.com or replacing blob in the path with raw. None of those actually worked.

However, to curl for example this file we can check the response headers which point us at the correct URL:

curl -v https://github.com/LibreOffice/dictionaries/raw/master/de/de_DE_frami.aff
> GET /LibreOffice/dictionaries/raw/master/de/de_DE_frami.aff HTTP/2
> Host: github.com
...
< HTTP/2 302 
< location: https://raw.githubusercontent.com/LibreOffice/dictionaries/master/de/de_DE_frami.aff

which allows us to download the raw file directly. And so,

curl -L https://github.com/LibreOffice/dictionaries/raw/master/de/de_DE_frami.aff

follows Github’s redirect automatically and downloads the raw file.

Upvotes: 1

Grazziani Xavier
Grazziani Xavier

Reputation: 23

You could publish (1) these js/css files in GitHub Pages, then you can reference (2) these files...

(1) Publish Original source: https://docs.github.com/en/pages/getting-started-with-github-pages/configuring-a-publishing-source-for-your-github-pages-site

You have to make your repo public or upgrade to a paid plan.

So you can go to "Settings / Code Automation / Pages". Then in "Build and Deployment" choose Source "Deploy from a branch" and after that select the branch name and folder.

You wait some minutes until deploy starts. In the end you can view the link for your project on "github.io" like this "https://username.github.io/projectname". From this moment you can try get your file, for example typing the url: https://username.github.io/projectname/js/script.js

(2) Reference the files

<link rel="stylesheet" href="https://username.github.io/projectname/css/style.css"/>
<script src="https://username.github.io/projectname/js/script.js"></script>

(END)

Don't use raw links.

Upvotes: 0

ggorlen
ggorlen

Reputation: 57175

Based on this answer and the JSDelivr docs, here's a script to help generate a JSDeliver link. Paste in a GitHub file URL and it should give you the corresponding JSDeliver URL. Please leave a comment if you find any issues; I haven't tested it extensively.

const createJSDelivrUrl = (ghUrl, {minify}) => {
  const jsDelivrPrefix = "https://cdn.jsdelivr.net/gh";
  const [username, repo, , version, ...path] = ghUrl
    .trim()
    .split("github.com/")[1]
    .split("/");
  const [file, ext] = path.at(-1).split(".");
  const finalPath = minify
    ? [...path.slice(0, -1), [file, "min", ext].join(".")]
    : path;
  return [
    jsDelivrPrefix,
    username,
    `${repo}@${version}`,
    ...finalPath,
  ].join("/");
};

const copyToClipboard = text => {
  const ta = document.createElement("textarea");
  ta.textContent = text;
  document.body.appendChild(ta);
  ta.select();
  document.execCommand("copy");
  document.body.removeChild(ta);
};

const handleChange = () => {
  try {
    const url = createJSDelivrUrl(ghUrl, {minify});
    out.innerHTML = `
      <button type="button">Copy</button>
      <a href="${url}">${url}</a>
    `;
    out.querySelector("button").addEventListener("click", e => {
      copyToClipboard(url);
    });
  } catch (err) {
    out.textContent = "Invalid GitHub URL";
  }
};

const out = document.querySelector(".out");
let minify = false;
let ghUrl = "";
document
  .querySelector('input[name="min"]')
  .addEventListener("change", e => {
    minify = e.target.checked;
    handleChange();
  });

document
  .querySelector('input[name="gh-url"]')
  .addEventListener("keyup", e => {
    ghUrl = e.target.value.trim();
    
    if (ghUrl) {
      handleChange();
    } else {
      out.textContent = "";
    }
  });
* {box-sizing: border-box;}
[name="gh-url"] {width: 100%;}
body {max-width: 600px;}
button {padding-right: 0.2em;}
<meta name="color-scheme" content="dark light">
<h3>GitHub to JSDelivr converter</h3>
<p>
  Paste a GitHub file URL like <a href="https://github.com/ggorlen/prettybt/blob/master/js/pbt.js">https://github.com/ggorlen/prettybt/blob/master/js/pbt.js</a> to generate a JSDeliver URL.
</p>
<input name="gh-url" placeholder="GH file URL">
<label>
  Minify <input name="min" type="checkbox">
</label>
<p class="out"></p>

Upvotes: 1

Farhad Sakhaei
Farhad Sakhaei

Reputation: 922

Use jsdelivr.com

Copied directly from https://www.jsdelivr.com/?docs=gh:

load any GitHub release, commit, or branch
note: we recommend using npm for projects that support it

https://cdn.jsdelivr.net/gh/user/repo@version/file

load jQuery v3.2.1

https://cdn.jsdelivr.net/gh/jquery/[email protected]/dist/jquery.min.js

use a version range instead of a specific version

https://cdn.jsdelivr.net/gh/jquery/[email protected]/dist/jquery.min.js

https://cdn.jsdelivr.net/gh/jquery/jquery@3/dist/jquery.min.js

omit the version completely to get the latest one

you should NOT use this in production

https://cdn.jsdelivr.net/gh/jquery/jquery/dist/jquery.min.js

add ".min" to any JS/CSS file to get a minified version

if one doesn't exist, we'll generate it for you

https://cdn.jsdelivr.net/gh/jquery/[email protected]/src/core.min.js

add / at the end to get a directory listing

https://cdn.jsdelivr.net/gh/jquery/jquery/

Upvotes: 14

jekewa
jekewa

Reputation: 279

Add a branch your project using the name "gh-pages" and then you'll (shortly after branching) be able to use a direct URL such as https://username.github.io/project/master/style.css (using your URL, and assuming "style.css" is a file in the "master" folder in the root of your "project" repository...and that your Github account is "username").

Upvotes: 15

Sista Fiolen
Sista Fiolen

Reputation: 786

GitHub Pages: https://yourusername.github.io/script.js
GitHub repo raw files: https://github.com/yourusername/yourusername.github.io/blob/master/script.js

Use GitHub Pages, DO NOT use raw files.

Reason: GitHub Pages are based on CDN, raw files are not. Accessing raw files will directly hit on GitHub servers and increase server load.

Upvotes: 23

KHAYRI R.R. WOULFE
KHAYRI R.R. WOULFE

Reputation: 321

If your webserver has active allow_url_include, GitHub serving the files as raw plain/text is not a problem since you can include the file first in a PHP script and modify its Headers to the proper MIME type.

Upvotes: -1

Benjamin Intal
Benjamin Intal

Reputation: 2815

You can link directly to raw files, but it's best not to do it since the raw files always get sent with a plain/text header and can cause loading problems.

Upvotes: 16

After searching for this same functionality, I ended up writing my own PHP script to act as a proxy. The trouble I kept running into is even when you get the RAW version/link from Github and link to it in your own page, the header sent over was 'text/plain' and Chrome was not executing my JavaScript file from Github. I also didn't like the other links posted for using third party services because of the obvious security/tampering issues possible.

So using this script, I can pass over the RAW link from Github, have the script set the correct headers, and then output the file as if it were coming from my own server. This script can also be used with a secure application to pull in non-secure scripts without throwing SSL errors warning of "Non-secure links used".

Linking:

<script src="proxy.php?link=https://raw.githubusercontent.com/UserName/repo/master/my_script.js"></script>

proxy.php

<?php
###################################################################################################################
# 
# This script can take two URL variables
# 
# "type"
#   OPTIONAL
#   STRING
#   Sets the type of file that is output
# 
# "link"
#   REQUIRED
#   STRING
#   The link to grab and output through this proxy script
# 
###################################################################################################################



# First we need to set the headers for the output file
# So check to see if the type is specified first and if so, then set according to what is being requested
if(isset($_GET['type']) && $_GET['type'] != ''){
    switch($_GET['type']){
        case 'css':
            header('Content-Type: text/css');
            break;

        case 'js':
            header('Content-Type: text/javascript');
            break;

        case 'json':
            header('Content-Type: application/json');
            break;

        case 'rss':
            header('Content-Type: application/rss+xml; charset=ISO-8859-1');
            break;

        case 'xml':
            header('Content-Type: text/xml');
            break;

        default:
            header('Content-Type: text/plain');
            break;
    }

# Otherwise, try and determine what file type should be output by the file extension from the link
}else{
    # See if we can find a file type in the link specified and set the headers accordingly

    # If css file extension is found, then set the headers to css format
    if(strstr($_GET['link'], '.css') != FALSE){
        header('Content-Type: text/css');

    # If javascript file extension is found, then set the headers to javascript format
    }elseif(strstr($_GET['link'], '.js') != FALSE){
        header('Content-Type: text/javascript');

    # If json file extension is found, then set the headers to json format
    }elseif(strstr($_GET['link'], '.json') != FALSE){
        header('Content-Type: application/json');

    # If rss file extension is found, then set the headers to rss format
    }elseif(strstr($_GET['link'], '.rss') != FALSE){
        header('Content-Type: application/rss+xml; charset=ISO-8859-1');

    # If css xml extension is found, then set the headers to xml format
    }elseif(strstr($_GET['link'], '.xml') != FALSE){
        header('Content-Type: text/xml');

    # If we still haven't found a suitable file extension, then just set the headers to plain text format
    }else{
        header('Content-Type: text/plain');
    }
}

# Now get the contents of our page we're wanting
$contents = file_get_contents($_GET['link']);

# And finally, spit everything out
echo $contents;
?>

Upvotes: -1

Related Questions