Github js file not loading (direct link)

I created a coding library for the public to use by put a <script> tag in the <head> tag but when I try to use the a function it says undefined. I linked the url to the index.js file but it doesn’t load it to the client.

<head> <script src="https://github.com/McJoe21/coderslib/blob/master/index.js"></script> </head> 

When I run a console.log(ranInteger(1,10)) which I have defined in my index.js file but I get a ranInteger is not defined error.

Add Comment
2 Answer(s)

Technically speaking, GitHub doesn’t allow source code to be accessed from their site like a CDN, however from This StackOverflow Question, there is a workaround. I wouldn’t recommend using it, but you can use "https://cdn.jsdelivr.net/gh/" to get your script to work (from user @anayarojo on StackOverflow).

The url in your case would look like this:

https://cdn.jsdelivr.net/gh/McJoe21/coderslib/index.js 

The pattern for the URL is: https://cdn.jsdelivr.net/gh/<username>/<repository>/<file>

Add Comment

The file you’re attempting to import is a GitHub viewer for a file. To import the raw data for that file, you’d want to use this code:

<script>    const source = 'https://raw.githubusercontent.com/McJoe21/coderslib/master/index.js';    fetch(source).then((response) => {       return response.text()    }).then((response) => {       eval(response);    }).catch((error) => {       console.error(`An error occured while attempting to load the "${source}" resource!`);       console.error(error);    }); </script> 

Since GitHub does not directly allow the import of their user content, you will need to wrap your source URL in the above fetch-eval block.

Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.