Skip to content

Instantly share code, notes, and snippets.

@tomhodgins tomhodgins/jic.js
Last active Dec 8, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.