懒惰加载github gist文件以在网站上显示源代码

时间:2011-04-15 06:06:22

标签: gist

我需要在网站帖子中包含几个要点,以展示源代码。目前,我使用脚本标记在HTML中的各个位置插入了多个要点,但是,这将是一个阻塞调用。那么,有没有办法动态加载要点并及时粘贴特定时间点。

我尝试过类似下面的内容: -

<html>
<body>
<div id="bookmarklet_1.js"></div>
<div id="bookmarklet_2.js"></div>
<div id="bookmarklet_3.js"></div>

var scriptMap = {'bookmarklet_1.js' : 'https://gist.github.com/892232.js?file=bookmarklet_1.js',
                 'bookmarklet_2.js' : 'https://gist.github.com/892234.js?file=bookmarklet_2.js',
                 'bookmarklet_3.js' : 'https://gist.github.com/892236.js?file=bookmarklet_3.js'};

var s, scr, holder; 
for(s in scriptMap){
    holder = document.getElementById(s);
    scr= document.createElement('script');
    scr.type= 'text/javascript';
    scr.src= scriptMap[s];
    holder.appendChild(scr); 
 }
 </script>
 </body>
 </html>

以上对我不起作用,似乎每个脚本都在内部编写document.write来编写CSS和源代码。有没有人试过这个或者让它运转起来?

3 个答案:

答案 0 :(得分:2)

我完全为此目的开始了一个项目。 Dynamically-embedded Gists

立即尝试:http://urlspoiler.herokuapp.com/gists?id=992729

使用上面的网址作为动态创建的iframe的src,或者添加&amp; format = html通过ajax获取Gist html代码段,然后将其放在任何您想要的位置。 (以上网址中的要点也恰好是如何使用此项目的文档。)

答案 1 :(得分:1)

我自己想完全做同样的事情(甚至删除了默认的gist样式链接) - 最终构建了一个处理document.write调用的“通用”脚本加载器:

https://github.com/kares/script.js

以下是如何使用它来嵌入要点(和馅饼):

https://github.com/kares/script.js/blob/master/examples/gistsAndPasties.html

答案 2 :(得分:0)

您现在可以使用JSONP直接获取HTML + CSS。

我在回复this question时写了一个更全面的答案,但关键是你可以使用JSONP获取HTML + CSS。

例如:https://gist.github.com/anonymous/5446989.json?callback=callback12345

callback12345({
    "description": "Function to load a Gist without an iframe",
    "public": true,
    ...
    "div": <HTML code>,
    "stylesheet": <URL of CSS file>
})