2012-02-05 29 views
4

我不確定在哪裏尋找這個。我正在創建一個下拉列表以選擇一個Gist ID,然後在佔位符div中生成它(嵌入)。jQuery - 動態加載Gist嵌入?

我以前生成的腳本,但隱藏,只需相對ID給他們。但是,這是極其緩慢甚至超過三個Gist嵌入。

我試過getScript,但我想在Gist嵌入代碼中的document.write只是不讓它滑動。

有人能指出我正確的方向嗎?

回答

6

這裏的問題是Gist嵌入JavaScript所使用的document.write在頁面加載後沒有執行。爲了解決這個問題,創建一個iframe,將其主體設置爲Gist嵌入JS,並設置onload事件以告知父級相應地調整iframe的大小。這裏是我的解決方案:https://gist.github.com/1748966

+0

完美。非常感謝你。 – 2012-02-06 07:17:13

7

雖然這可能是當時最好的答案,但我相信現在有更好的答案。

對於給定的要點,例如https://gist.github.com/anonymous/5446951,你可以在https://gist.github.com/anonymous/5446989.json訪問包含HTML標記和CSS的URI要點的JSON對象 - 它看起來是這樣的:

{ 
    "description": ..., 
    "public":true, 
    ... 
    "div": <HTML code>, 
    "stylesheet": <URI of CSS file> 
} 

事實上,你可以得到這個數據,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); 
} 
+0

事實上 - 你已經標記了這個'jQuery',這應該使JSONP調用變得更容易。 – cloudfeet 2013-04-23 20:18:45