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

点击按钮添加GitHub Gist时动态脚本不触发、Gist未显示问题

动态插入GitHub Gist不显示的解决方案

问题根因

GitHub官方提供的Gist .js 加载脚本依赖document.write()方法注入内容,当页面完成初始渲染后再动态插入这个script标签时,document.write()的执行上下文已发生变化,无法正常把Gist内容插入到期望位置,部分浏览器甚至会主动阻止页面加载完成后的document.write调用,避免覆盖已有页面内容。

修复方案

方案1:使用Gist提供的回调参数手动挂载内容(推荐)

此方案可以精准控制Gist的挂载位置,无需额外适配:

function createGist(gistId = "bd10e846c6eae4419c3041f3da1b82a0"){
    // 创建Gist专属挂载容器
    const gistContainer = document.createElement("div");
    gistContainer.id = `gist-${gistId}`;
    // 可修改为你需要挂载的父元素,无需固定插入body末尾
    document.body.appendChild(gistContainer);

    // 定义全局回调接收Gist返回数据
    window[`gistCallback_${gistId}`] = function(gistData) {
        // 加载Gist专属样式
        const styleLink = document.createElement("link");
        styleLink.rel = "stylesheet";
        styleLink.href = gistData.stylesheet;
        document.head.appendChild(styleLink);
        // 插入Gist渲染内容
        gistContainer.innerHTML = gistData.div;
        // 清理全局回调避免内存泄漏
        delete window[`gistCallback_${gistId}`];
    }

    // 加载带回调参数的Gist脚本
    const script = document.createElement("script");
    script.src = `https://gist.github.com/snakifyanswers/${gistId}.js?callback=gistCallback_${gistId}`;
    document.body.appendChild(script);
}

方案2:使用iframe嵌入(更简单)

如果不需要自定义挂载逻辑,可以直接用iframe嵌入Gist的渲染页面:

function createGist(gistId = "bd10e846c6eae4419c3041f3da1b82a0"){
    const gistIframe = document.createElement("iframe");
    gistIframe.src = `https://gist.github.com/snakifyanswers/${gistId}.pibb`;
    gistIframe.style.width = "100%";
    gistIframe.style.border = "0";
    // 可自行调整iframe高度,也可以加载完成后自适应
    gistIframe.style.height = "400px";
    document.body.appendChild(gistIframe);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:45:03