Link and execute external JavaScript file hosted on GitHub

前端 未结 15 1173
感动是毒
感动是毒 2020-11-22 04:08

When I try to change the linked reference of a local JavaScript file to a GitHub raw version my test file stops working. The error is:

Refused to exe

15条回答
  •  逝去的感伤
    2020-11-22 04:23

    There is a good workaround for this, now, by using jsdelivr.net.

    Steps:

    1. Find your link on GitHub, and click to the "Raw" version.
    2. Copy the URL.
    3. Change raw.githubusercontent.com to cdn.jsdelivr.net
    4. Insert /gh/ before your username.
    5. Remove the branch name.
    6. (Optional) Insert the version you want to link to, as @version (if you do not do this, you will get the latest - which may cause long-term caching)

    Examples:

    http://raw.githubusercontent.com////path/to/file.js
    

    Use this URL to get the latest version:

    http://cdn.jsdelivr.net/gh///path/to/file.js
    

    Use this URL to get a specific version or commit hash:

    http://cdn.jsdelivr.net/gh//@/path/to/file.js
    

    For production environments, consider targeting a specific tag or commit-hash rather than the branch. Using the latest link may result in long-term caching of the file, causing your link to not be updated as you push new versions. Linking to a file by commit-hash or tag makes the link unique to version.


    Why is this needed?

    In 2013, GitHub started using X-Content-Type-Options: nosniff, which instructs more modern browsers to enforce strict MIME type checking. It then returns the raw files in a MIME type returned by the server, preventing the browser from using the file as-intended (if the browser honors the setting).

    For background on this topic, please refer to this discussion thread.

提交回复
热议问题