Link and execute external JavaScript file hosted on GitHub

前端 未结 15 1171
感动是毒
感动是毒 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:27

    GitHub Pages is GitHub’s official solution to this problem.

    raw.githubusercontent makes all files use the text/plain MIME type, even if the file is a CSS or JavaScript file. So going to https://raw.githubusercontent.com/‹user›/‹repo›/‹branch›/‹filepath› will not be the correct MIME type but instead a plaintext file, and linking it via or won’t work—the CSS won’t apply / the JS won’t run.

    GitHub Pages hosts your repo at a special URL, so all you have to do is check-in your files and push. Note that in most cases, GitHub Pages requires you to commit to a special branch, gh-pages.

    On your new site, which is usually https://‹user›.github.io/‹repo›, every file committed to the gh-pages branch (the most recent commit) is present at this url. So then you can link to your js file via , and this will be the correct MIME type.

    Do you have build files?

    Personally, my recommendation is to run this branch parallel to master. On the gh-pages branch, you can edit your .gitignore file to check in all the dist/build files you need for your site (e.g. if you have any minified/compiled files), while keeping them ignored on your master branch. This is useful because you typically don’t want to track changes in build files in your regular repo. Every time you want to update your hosted files, simply merge master into gh-pages, rebuild, commit, and then push.

    (protip: you can merge and rebuild in the same commit with these steps:)

    $ git checkout gh-pages
    $ git merge --no-ff --no-commit master  # prepare the merge but don’t commit it (as if there were a merge conflict)
    $ npm run build                         # (or whatever your build process is)
    $ git add .                             # stage the newly built files
    $ git merge --continue                  # commit the merge
    $ git push origin gh-pages
    

提交回复
热议问题