jQuery - 动态加载Gist嵌入?

Tal*_*son 4 jquery gist

我不知道在哪里寻找这个.我想创建一个下拉列表来选择一个Gist ID,然后在占位符div中生成它(嵌入).

我以前生成了脚本但隐藏了,只是通过rel ID显示它们.但是,即使超过三个Gist嵌入,这也非常缓慢.

我试过了getScript,但我想document.write在Gist中嵌入代码只是不让它滑动.

有人能指出我正确的方向吗?

Jer*_*Lee 7

这里的问题是Gist embed JavaScript使用的document.write在页面加载后不会执行.要解决这个问题,请创建一个iframe,将其主体设置为Gist嵌入JS,并设置一个onload事件以告诉父级相应地调整iframe的大小.这是我的解决方案:https://gist.github.com/1748966


clo*_*eet 7

虽然这可能是当时最好的答案,但我相信现在有一个更好的答案.

对于给定的要点,例如https://gist.github.com/anonymous/5446951,您可以访问包含Gist的HTML标记和CSS URI的JSON对象,网址为https://gist.github.com/anonymous/5446989 .json - 它看起来像:

{
    "description": ...,
    "public":true,
    ...
    "div": <HTML code>,
    "stylesheet": <URI of CSS file>
}
Run Code Online (Sandbox Code Playgroud)

实际上,您可以将此数据作为JSONP获取:https://gist.github.com/anonymous/5446989.json callback = callback12345

因此,要在没有iframe的情况下动态加载Gist :

function loadGist(element, gistId) {
    var callbackName = "gist_callback";
    window[callbackName] = function (gistData) {
        delete window[callbackName];
        var html = '<link rel="stylesheet" href="' + escapeHtml(gistData.stylesheet) + '"></link>';
        html += gistData.div;
        element.innerHTML = html;
        script.parentNode.removeChild(script);
    };
    var script = document.createElement("script");
    script.setAttribute("src", "https://gist.github.com/" + gistId + ".json?callback=" + callbackName);
    document.body.appendChild(script);
}
Run Code Online (Sandbox Code Playgroud)