开发者

Lazy load github gist files to display source code on the website

I have a couple of gists which I need to include in a website post to showcase the source code. Currently, I'm inlining each of the multiple gists at various places in the HTML with script tags, however, this would be a blocking call. So, is there a way to dynamically load the gists and paste it specific points in time.

I tried something like below :-

<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?fi开发者_StackOverflow中文版le=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>

The above didn't work for me, it seems that each script is doing a document.write internally to write the CSS and soure code. Has anyone tried this before or got it working ?


I started a project exactly for this purpose. Dynamically-embedded Gists

Try it now: http://urlspoiler.herokuapp.com/gists?id=992729

Use the above url as the src of a dynamically-created iframe, or add &format=html to get the Gist html snippet via ajax, then put it anywhere you want. (The gist in the above url also happens to be the documentation for how to use this project.)


I myself wanted to do exactly the same thing (with the addition of even removing the default gist style link) - ended up building a "generic" script loader that handles document.write calls :

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

Here's how one can use it for embedding gists (and pasties) :

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


You can now get the HTML + CSS directly using JSONP.

I wrote a fuller answer in response to this question, but the key is that you can get the HTML + CSS using JSONP.

For example: 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>
})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜