如何通过jsdelivr CDN加载GitHub项目并托管静态资源?
Hey there, let's break down exactly how to use jsDelivr (a reliable free CDN) to host your static assets from that GitHub repo of yours. It's straightforward once you get the hang of the URL structure.
First, Get Your Repo's Base CDN Path
jsDelivr uses a simple pattern for GitHub repos:https://cdn.jsdelivr.net/gh/shaikatssj/scodec-cdn@[BRANCH/VERSION]/
- Swap
[BRANCH/VERSION]with your default branch name (likemainif that's what you use) or a specific release tag/commit hash. Using a tag/hash is smarter for stability—your users won't get unexpected updates if you push changes to the main branch later.
Link to Your Files Directly
Once you have that base path, just add the exact file path from your repo to the end. Here are examples for each file type:
CSS Files
Suppose your main stylesheet is at css/main.css in the repo. Drop this into your HTML's <head>:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/shaikatssj/scodec-cdn@main/css/main.css">
JS Files
If you have a script at js/app.js, add this before your closing </body> tag:
<script src="https://cdn.jsdelivr.net/gh/shaikatssj/scodec-cdn@main/js/app.js"></script>
Font Files
For fonts, you'll reference the CDN URL directly in your CSS @font-face rule. Let's say you have a font file at fonts/custom-font.ttf:
@font-face { font-family: 'CustomFont'; src: url('https://cdn.jsdelivr.net/gh/shaikatssj/scodec-cdn@main/fonts/custom-font.ttf') format('truetype'); /* Add other font formats (woff, woff2) if you have them for better browser support */ }
Quick Pro Tips
- Verify paths first: Before adding links to your site, paste the full CDN URL into your browser to make sure the file loads. Typos in file paths are the most common issue here.
- Stick to versioned links: If you plan to update your repo regularly, use a release tag (like
v1.0.0) instead of the main branch. This ensures users get a consistent version until you intentionally update the tag. - Browser caching: jsDelivr automatically caches your files globally, so your users will load assets faster no matter where they are.
That's all you need to do! Now you can load all your static assets directly from the CDN without managing your own hosting.
内容的提问来源于stack exchange,提问作者user5724063

