Skip to content

Instantly share code, notes, and snippets.

@CTimmerman
Created March 23, 2015 14:31
Show Gist options
  • Save CTimmerman/3c1899c6e5d5bfb925c5 to your computer and use it in GitHub Desktop.
Save CTimmerman/3c1899c6e5d5bfb925c5 to your computer and use it in GitHub Desktop.
highlight.js
// Highlight 22 popular code types. TODO: Inline for speed and security.
function loadjscssfile(filename, filetype){ // http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
if(filetype=="js"){
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
}
else if(filetype=="css"){
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if(typeof fileref!="undefined") document.getElementsByTagName("head")[0].appendChild(fileref)
}
loadjscssfile("//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/vs.min.css", "css")
loadjscssfile("//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js", "js")
setTimeout("var a = document.querySelectorAll('.code'); for(var i=0; i < a.length; ++i) hljs.highlightBlock(a[i])", 600)
@CTimmerman
Copy link
Author

CTimmerman commented Nov 21, 2017

The trick is the timeout. For dynamic content, a callback would be better. Even polling is more reliable than a single timeout, but this passed every test thrown at it, so according to TDD it's done. Also, highlight.js now supports 176 languages.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment