Created
February 20, 2017 15:51
-
-
Save iamstuartwilson/c409c5abc0742c14082ace7983284259 to your computer and use it in GitHub Desktop.
Extract @imports in <style> elements to individual <link> elements
This file contains hidden or 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
(function importsToLinks() { | |
var i; | |
var n; | |
var imports; | |
var newLinkElement; | |
var $inlineStyleElements = document.querySelectorAll('style'); | |
for (i = 0; i < $inlineStyleElements.length; i ++) { | |
imports = $inlineStyleElements[i].innerText.match(/(@import) (url)\(([^>]*?)\)/g); | |
if (imports && typeof imports === 'object' && 'length' in imports) { | |
for (n = 0; n < imports.length; n ++) { | |
newLinkElement = document.createElement('link'); | |
newLinkElement.rel = 'stylesheet'; | |
newLinkElement.type = 'text/css'; | |
newLinkElement.href = imports[n].split('"')[1]; | |
document.head.appendChild(newLinkElement); | |
$inlineStyleElements[i].innerText = $inlineStyleElements[i].innerText.replace(imports[n], ''); | |
} | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment