You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GitHub README中SVG徽章无法加载问题排查求助

问题

我尝试创建GitHub README徽章,但SVG图片无法在README中加载。当我使用![](https://atcoder.junah.dev/v1/generate_badge?name=junah)在GitHub README中加载图片时,出现“Error Fetching Resource”错误(相关截图:https://i.sstatic.net/nkwCN.png、https://i.sstatic.net/YZBf2.png)。但该SVG能在Stack Overflow等其他网站正常显示,请问这是什么原因?

以下是我的Lambda函数代码,完整代码见仓库:https://github.com/junah201/Atcoder-readme-stats

def lambda_handler(event, context):
    username = event.get("queryStringParameters", {}).get("name", None)

    # 获取数据的代码

    svg = '''\
<?xml version="1.0" encoding="UTF-8"?>
<svg
    width="350"
    height="170"
    viewBox="0 0 350 170"
    fill="none"
    version="1.1"
    xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    xml:space="preserve"
>
    <style type="text/css">
        @import url('https://fonts.googleapis.com/css2?family=Inter');

        .username {{
            font-family: 'Inter', sans-serif;
            font-size: 20px;
            font-weight: bold;
        }}
        /* 其他CSS代码 */
    </style>
    <defs>
        <linearGradient id="gradient" x1="0" y1="0" x2="286.703" y2="200.752" gradientUnits="userSpaceOnUse">
            <stop stop-color="{darker}"/>
            <stop offset="0.8" stop-color="{darker}"/>
            <stop offset="1" stop-color="{color}"/>
        </linearGradient>
    </defs>
    <rect width="350" height="170" fill="url(#gradient)" rx = "6"/>
    <g>
        /* 其他SVG代码 */
    </g>
</svg>
    '''.format(
        # 格式化参数代码
    )

    return {
        'statusCode': 200,
        'body': svg,
        'headers': {
            'Content-Type': 'image/svg+xml',
            'Cache-Control': 'max-age=1800'
        }
    }
分析与解决方法

GitHub对嵌入README的外部SVG有严格的安全限制,这是加载失败的核心原因,具体问题和解决办法如下:

  • 外部字体引用被拦截
    你的SVG通过@import引入了Google Fonts的外部字体,GitHub会拦截这类跨域外部资源请求以防范安全风险,直接导致SVG渲染失败。而Stack Overflow等平台对外部资源的限制更宽松,所以能正常显示。

  • SVG安全扫描机制
    GitHub会对嵌入的SVG进行XSS安全检查,如果SVG包含外部资源引用、脚本等可能的风险内容,会直接阻止加载。

针对这些问题,可以按以下方式解决:

  1. 内联字体资源
    将Inter字体转换为Base64编码,直接嵌入到SVG的<style>标签中,用@font-face定义字体,彻底消除外部依赖。可以用在线工具将字体文件转为Base64编码,替换原有的@import语句。
  2. 移除所有外部依赖
    确保SVG不依赖任何外部资源(包括字体、图片、外部样式表),所有样式和资源都内嵌在SVG内部。
  3. 验证HTTP响应头
    确认Lambda返回的Content-Type确实是image/svg+xml,同时检查是否存在其他影响加载的响应头(比如X-Content-Type-Options需设置为nosniff)。
  4. 测试最简SVG
    先创建一个不含任何外部引用的简单SVG(比如仅包含一个矩形和文本),测试能否在GitHub README中正常加载,排除其他潜在问题。

内容的提问来源于stack exchange,提问作者Junah201

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 21:00:32