How to import Files directly from GitHub

Lukas Gamper
2 min readJun 10, 2021
Photo by Philipp Katzenberger on Unsplash

Since all evergreen browsers support dynamic import, it’s appears convenient to load some scripts directly from GitHub. But GitHub is not a content delivery network (CDN). It delivers raw files always with the wrong content-type header (its always «text/plain» instead of «text/css» or «application/javascript») and it enforces strict rate limits.

Thankfully, there are some CDN’s serving directly from GitHub:

raw.githack.com

GitHack serves raw files directly from GitHub source code with proper content-type headers.

To get the CDN urls, copy the raw url of the file you want to import into your script. Every file on the GitHub webpage, has a button to get the raw url.

Now paste the raw url into the raw.githack.com form and it create two CDN urls:

  • The first for production which is hosted on CloudFlare and bound to the current commit. If you want to access your file in a production application, make sure to take this url. If you push a new version to GitHub, you have to create a new url.
  • The second is for development. If you push a commit to GitHub, the changes are reflected within minutes. This url is meant for development, for production use the first url.

cdn.jsdelivr.net

JSDelivr has a nice integration with GitHub. The following raw GitHub url

https://raw.githubusercontent.com/usystems/webling-plugins/main/examples/member-map/index.js

can be accessed through the JSDelivr by

https://cdn.jsdelivr.net/gh/usystems/webling-plugins@latest/examples/member-map/index.js

How does it work

  1. Replace http://raw.githubusercontent.com/ with https://cdn.jsdelivr.net/gh/. Make sure you don’t forget the /gh/ segment.
  2. Remove «main» from the url, because JSDelivr always takes the file from the main branch.
  3. Add a GitHub tag after the repository. Either a tag from GitHub like 1.0.0 or latest for the latest version of this file.

If you don’t add the latest tag, JSDelivr will cache your file and always deliver the same file.

Forgetting to add the latest tag to your url, JSDelivr will update to a new version after some time. After committing a new version it may take some time until JSDelivr updates its caches.

Conclusion

If you want to use a file directly from GitHub, do never use the raw GitHub url, because GitHub will block your account pretty fast. Use a CDN like GitHack or JSDelivr.

--

--