Last active
May 16, 2018 13:46
-
-
Save mbaxter91288/2a63a687683163bc803049b09b30d597 to your computer and use it in GitHub Desktop.
Dynamically turn Gist urls into scripts. This is useful when using a CMS like Webflow that doesn't allow you to create <script> or <code> tags directly in it's RichText Editor.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('body').html($('body').html().replace(/~\[(.*?)\]~/g, "<div class=\"js-gist\" data-src=\"$1\">$1</div>")); | |
$('.js-gist[data-src]').each(function(){ | |
// we need to store $this for the callback | |
var $this = $(this); | |
// load gist as json instead with a jsonp request | |
// NOTE: currently this only works for single files, if you want the whole gist, use this | |
// $.getJSON( $this.attr('data-src') + '?callback=?', function( data ) { | |
$.getJSON( $this.attr('data-src') + '&callback=?', function( data ) { | |
// replace script with gist html | |
$this.html(data.div); | |
// load the stylesheet, but only once… | |
add_stylesheet_once( data.stylesheet ); | |
}); | |
}); | |
function add_stylesheet_once( url ){ | |
$head = $('head'); | |
if( $head.find('link[rel="stylesheet"][href="'+url+'"]').length < 1 ) | |
$head.append('<link rel="stylesheet" href="'+ url +'" type="text/css" />'); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- notice we're referencing the .json version of the embed script, not the .js --> | |
<!-- single files --> | |
~[https://gist.github.com/mbaxter91288/2a63a687683163bc803049b09b30d597.json?file=dynamically-load-gist.js]~ | |
<!-- whole gist --> | |
~[https://gist.github.com/mbaxter91288/2a63a687683163bc803049b09b30d597.json]~ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment