Last active
October 16, 2023 03:39
-
-
Save nuxodin/b8a83c925227e85b1fdf0e7b5baff3e2 to your computer and use it in GitHub Desktop.
Polyfill "style once" hopefully standardised soon :)
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
const selector = 'link[rel="stylesheet"], style'; | |
onElement(selector, function(el){ // NOT IMPLEMENTED IN THIS SCRIPT | |
// checks all styleSheets and importRules, todo store urls global and check all if used url found | |
// console.log(el.sheet) | |
checkAllSheets() | |
}); | |
function checkAllSheets(){ | |
const urls = {}; | |
for (let sheet of document.styleSheets) checkSheet(sheet); | |
function checkSheet(sheet){ | |
try { // firefox fails sometimes if we access sheet.cssRules immediate after found it | |
checkImportRules(sheet.cssRules); | |
} catch (e) { | |
//console.log('fail',sheet, e) // | |
} | |
if (!sheet.href) return; | |
const hasAttribute = sheet.ownerNode && sheet.ownerNode.hasAttribute('once'); | |
const hasMediaOnce = medialist_has(sheet.media, 'once'); | |
if (hasAttribute || hasMediaOnce) { | |
sheet.disabled = !!urls[sheet.href]; | |
urls[sheet.href] = 1; | |
} | |
} | |
function checkImportRules(rules){ | |
for (let rule of rules) { | |
if (rule instanceof CSSImportRule) checkSheet(rule.styleSheet); | |
} | |
} | |
} | |
function medialist_has(mediaList, wanted){ | |
for (let medium of mediaList) { | |
if (medium === wanted) return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Handle once in style-links
And css imports