How to load external JavaScript from GitHub repository in HTML

I’m having trouble loading a JavaScript file directly from GitHub into my HTML page. When I use a local copy of the script, everything works perfectly fine. But when I try to reference the same file from GitHub’s raw content URL, my browser throws an error.

The error message says something about MIME type being text/plain instead of executable, and that strict MIME type checking prevents the script from running.

Here’s what works locally:

<script src="my-editor.js"></script>

But this doesn’t work:

<script src="https://raw.githubusercontent.com/user/repo/main/my-editor.js"></script>

Is there any way around this MIME type issue? Maybe there’s a different URL format or a CDN service that can serve GitHub files with proper headers? I’d really like to avoid downloading and hosting the file myself if possible.

if u have access, just enable GitHub Pages in your repo settings. then, use the URL https://username.github.io/repo/my-editor.js to load your JS file. it’s smooth and avoids any third-party services!

Browsers got way stricter with MIME type restrictions lately. Hit this same problem last month trying to load a script straight from GitHub. The raw.githubusercontent.com domain serves everything as text/plain to block XSS attacks. Two fixes that worked for me: Enable GitHub Pages on your repo and use that URL instead - it’ll serve your JS files with proper MIME types. Or try statically.io, which acts like a CDN but usually has better uptime. Just swap your GitHub raw URL to https://cdn.statically.io/gh/user/repo/main/my-editor.js and you’re good.

GitHub serves raw files as plain text for security reasons, which causes the MIME type error. Besides jsdelivr, you’ve got unpkg.com (https://unpkg.com/user/repo@main/my-editor.js) or gitcdn.xyz (https://gitcdn.xyz/repo/user/repo/main/my-editor.js). I prefer gitcdn for quick prototypes since it doesn’t need your repo to be an npm package like unpkg does. All these CDNs set the proper Content-Type header to application/javascript, fixing the MIME error.

try using jsdelivr CDN - just change the URL to https://cdn.jsdelivr.net/gh/user/repo@main/my-editor.js. it serves files with the right mime types, so u shouldn’t get that error.

The Problem:

You’re encountering a MIME type error when loading a JavaScript file directly from a GitHub raw content URL into your HTML page. Your local copy works fine, but the GitHub version is served as text/plain, preventing execution due to browser security restrictions.

:thinking: Understanding the “Why” (The Root Cause):

Browsers have tightened security around script execution to mitigate Cross-Site Scripting (XSS) attacks. GitHub’s raw content URLs serve files with a text/plain MIME type by default as a security precaution. This prevents malicious scripts from being injected into your webpage. Therefore, directly using raw.githubusercontent.com for JavaScript files will often result in the MIME type error you’re seeing.

:gear: Step-by-Step Guide:

This guide focuses on automating the process of fetching and serving your JavaScript files from GitHub, eliminating reliance on external CDNs and ensuring reliable, fast loading with correct headers. This is a more robust solution than simply using a CDN, although CDNs are a good temporary solution.

Step 1: Set up a Webhook in your GitHub Repository:

  1. Navigate to your GitHub repository’s settings.
  2. Go to the “Webhooks” section.
  3. Click “Add webhook.”
  4. In the “Payload URL,” enter the URL of your server that will receive the webhook notifications (this will be part of your custom automation setup described below).
  5. Select “application/json” as the Content type.
  6. Choose which events trigger webhook (e.g., “Push” for updates).
  7. Click “Add webhook.”

Step 2: Create an Automation Script (e.g., using Node.js):

You’ll need a server-side script to:

  1. Receive webhook notifications from GitHub.
  2. Fetch the updated JavaScript file from the GitHub raw content URL using a library like axios or node-fetch.
  3. Serve the file with the correct Content-Type: application/javascript header.

A simple example (Node.js with Express.js):

const express = require('express');
const axios = require('axios');
const app = express();
const port = 3000;

app.get('/my-editor.js', async (req, res) => {
  try {
    const response = await axios.get('https://raw.githubusercontent.com/user/repo/main/my-editor.js', { responseType: 'stream' });
    res.setHeader('Content-Type', 'application/javascript');
    response.data.pipe(res);
  } catch (error) {
    console.error('Error fetching file:', error);
    res.status(500).send('Error fetching JavaScript file.');
  }
});

app.listen(port, () => console.log(`Server listening on port ${port}`));

Step 3: Update Your HTML:

Change your <script> tag to point to your new server:

<script src="http://your-server-address:3000/my-editor.js"></script>

Step 4: Deploy and Test:

Deploy your server and test the changes. Remember to replace placeholders like your-server-address and the GitHub URL with your actual values.

:mag: Common Pitfalls & What to Check Next:

  • Server-Side Errors: Double-check your server logs for any errors during file fetching or serving.
  • Webhook Configuration: Verify that the webhook is correctly configured in GitHub and that your server is receiving notifications.
  • CORS Issues (If applicable): If your server and your webpage are on different domains, you might need to handle CORS (Cross-Origin Resource Sharing) to prevent browser security restrictions.
  • File Path: Ensure the path to my-editor.js in your GitHub repo and your server-side script is correct.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.