Home > Web Front-end > JS Tutorial > How Can I Successfully Link and Execute External JavaScript Files Hosted on GitHub?

How Can I Successfully Link and Execute External JavaScript Files Hosted on GitHub?

Linda Hamilton
Release: 2024-12-01 01:31:11
Original
737 people have browsed it

How Can I Successfully Link and Execute External JavaScript Files Hosted on GitHub?

Linking and Executing External JavaScript Files Hosted on GitHub

In an attempt to load an external JavaScript file from GitHub Raw, you may encounter the error "Refused to execute script... MIME type (text/plain) is not executable." This is due to the X-Content-Type-Options: nosniff header set by GitHub, which enforces strict MIME type checking.

Solution: jsdelivr.net

However, jsdelivr.net provides a workaround for this issue. By modifying the GitHub Raw URL and adding it to jsdelivr.net, you can load the external script successfully.

Steps to Modify GitHub Raw URL for jsdelivr.net:

  1. Find the GitHub Raw URL and click on the "Raw" version.
  2. Copy the URL.
  3. Replace raw.githubusercontent.com with cdn.jsdelivr.net.
  4. Insert /gh/ before your GitHub username.
  5. Remove the branch name (if present).
  6. Optionally, specify the version you want to link to (e.g., @version) or remove it to get the latest.

Examples:

  • To get the latest version:
http://cdn.jsdelivr.net/gh/<username>/<repo>/path/to/file.js
Copy after login
  • To get a specific version or commit hash:
http://cdn.jsdelivr.net/gh/<username>/<repo>@<version or hash>/path/to/file.js
Copy after login

Considerations for Production Environments:

For production environments, it is advisable to target a specific tag or commit hash instead of the branch. Relying on the latest link can result in prolonged caching, preventing the file from updating when you push new versions. By using a commit hash or tag, you ensure the link is unique to the version.

Background on MIME Type Checking:

GitHub implemented X-Content-Type-Options: nosniff in 2013 to enforce strict MIME type checking in modern browsers. This action prevents the browser from using the file as intended if it honors the setting.

The above is the detailed content of How Can I Successfully Link and Execute External JavaScript Files Hosted on GitHub?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template