Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Last active December 8, 2017 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomhodgins/b8697d6599b2cda60bb7e77e5f2387fe to your computer and use it in GitHub Desktop.
Save tomhodgins/b8697d6599b2cda60bb7e77e5f2387fe to your computer and use it in GitHub Desktop.
Use this to interpret JS inside ${} anywhere inside <style> innerHTML or the content of external <link rel=stylesheet href> tags
// Interpolate JS from inside <style> and <link> tags with ${}
var JSinCSS = {}
JSinCSS.load = function() {
var style = document.getElementsByTagName('style')
for (i = 0; i < style.length; i++) {
JSinCSS.process(style[i], style[i].innerHTML)
}
var link = document.getElementsByTagName('link')
for (i = 0; i < link.length; i++) {
var currentLink = link[i]
if (currentLink.href && currentLink.rel == 'stylesheet') {
(function() {
var xhr = new XMLHttpRequest
xhr.open('GET', currentLink.href, true)
xhr.send(null)
xhr.onreadystatechange = function() {
JSinCSS.process(currentLink, xhr.responseText)
}
})()
}
}
}
JSinCSS.process = function(tag, stylesheet) {
if (stylesheet) {
var event = ['load', 'resize', 'input', 'click']
var css = new Function('return `' + stylesheet + '`')
for (var j=0; j<event.length; j++) {
if (!tag.getAttribute('data-populated')) {
var style = document.createElement('style')
style.innerHTML = css()
tag.setAttribute('data-populated', true)
style.setAttribute('data-populated', true)
document.head.appendChild(style)
}
window.addEventListener(event[j], function(e) {
if (style) {
style.innerHTML = css()
}
})
}
}
}
window.addEventListener('load', JSinCSS.load)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment