Last active
December 23, 2015 01:09
-
-
Save benknight/6558278 to your computer and use it in GitHub Desktop.
Code for applying JavaScript and CSS code from a Gist to a page. (This is *so* meta.)
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
<h1>Apply Gist Bookmarklet</h1> | |
Drag me into the bookmarks bar:<br> | |
<a href="javascript:(function()%7Bvar%20gist_id%3Dprompt(%27What%E2%80%99s%20the%20Gist%20ID%3F%27)%3Bvar%20css%3D%5B%5D%3Bvar%20js%3D%5B%5D%3Bvar%20applyCSS%3Dfunction()%7Bfor(var%20x%20in%20css)%7Bvar%20style%3Ddocument.createElement(%27style%27)%3Bstyle.innerHTML%3Dcss%5Bx%5D%3Bdocument.head.appendChild(style)%3B%7D%7D%3Bvar%20applyJS%3Dfunction()%7Bfor(var%20x%20in%20js)%7Bvar%20script%3Ddocument.createElement(%27script%27)%3Bscript.innerHTML%3Djs%5Bx%5D%3Bdocument.body.appendChild(script)%3B%7D%7D%3Bvar%20xhr%3Dnew%20XMLHttpRequest()%3Bxhr.open(%27GET%27,%27https://api.github.com/gists/%27%2Bgist_id,true)%3Bxhr.onload%3Dfunction()%7Bvar%20data%3DJSON.parse(this.responseText)%3Bfor(var%20file%20in%20data.files)%7Bif(data.files%5Bfile%5D.language%3D%3D%27CSS%27)%7Bcss.push(data.files%5Bfile%5D.content)%3B%7Dif(data.files%5Bfile%5D.language%3D%3D%27JavaScript%27)%7Bjs.push(data.files%5Bfile%5D.content)%3B%7D%7DapplyCSS()%3BapplyJS()%3B%7D%3Bxhr.onerror%3Dfunction()%7Bconsole.log(%27Failed%20to%20load%20Gist:%20%27%2Brequest.gist)%3B%7D%3Bxhr.send()%3B%7D())%3B">Apply Gist</a> |
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
var applyGist = function (gist) { | |
var css = []; | |
var js = []; | |
var applyCSS = function () { | |
for (var x in css) { | |
var style = document.createElement('style'); | |
style.innerHTML = css[x]; | |
document.head.appendChild(style); | |
} | |
} | |
var applyJS = function () { | |
for (var x in js) { | |
var script = document.createElement('script'); | |
script.innerHTML = js[x]; | |
document.body.appendChild(script); | |
} | |
} | |
var xhr = new XMLHttpRequest(); | |
xhr.onload = function () { | |
var data = window.JSON.parse(this.responseText); | |
for (var file in data.files) { | |
if (data.files[file].language == 'CSS') { | |
css.push(data.files[file].content); | |
} | |
if (data.files[file].language == 'JavaScript') { | |
js.push(data.files[file].content); | |
} | |
} | |
// Apply CSS, then JS. | |
applyCSS(); | |
applyJS(); | |
}; | |
xhr.onerror = function() { | |
console.log('Failed to load Gist: ' + gist); | |
}; | |
xhr.open('GET', 'https://api.github.com/gists/' + gist, true); | |
xhr.send(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment