Last active
December 8, 2017 17:19
-
-
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
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
// 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