Skip to content

Instantly share code, notes, and snippets.

@nuxodin
Last active October 16, 2023 03:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nuxodin/b8a83c925227e85b1fdf0e7b5baff3e2 to your computer and use it in GitHub Desktop.
Save nuxodin/b8a83c925227e85b1fdf0e7b5baff3e2 to your computer and use it in GitHub Desktop.
Polyfill "style once" hopefully standardised soon :)
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;
}
}
@nuxodin
Copy link
Author

nuxodin commented Mar 23, 2021

Handle once in style-links

<link rel=stylesheet once href="...">

And css imports

 @import url("bluish.css") once;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment