I' trying to create a function that simultaneously checks if a link to a certain CSS style sheet exists in the document and/or, if it doesn't, creates the link and returns the Javascript object of that linked stylesheet:
(function(doc) {
const sheets = doc.styleSheets;
const newSheet_path = location.origin + '/newSheet.css';
const newSheet = sheets => {
let sheetExists;
for(let sheet in sheets) {
if(sheets[sheet].href === newSheet_path) {
sheetExists = sheets[sheet];
}
}
if(!sheetExists) {
let addSheet = doc.createElement('link');
addSheet.setAttribute('rel', 'stylesheet');
addSheet.setAttribute('href', 'newSheet.css');
doc.head.appendChild(addSheet);
return addSheet;
} else {
return sheetExists;
}
}
console.log(newSheet(sheets));
}(window.document));
With this code, it returns the link
element if the sheet doesn't exist, which makes sense, but I need the Javascript object associated with it. I've tried replacing the addSheet return statement with something like this:
return Array.from(sheets).pop();
which just returns any existing sheet before the new one, and also this:
return Array.from(sheets).find((s,i,S) => S[i].href === newSheet_path);
but that comes back undefined
. If I'm guessing correctly, it's because sheets
is defined as the list of stylesheets before the new one gets added and as such, the variable doesn't get redefined with the new sheet included. I tried redefining it just before the return statement--
sheets = doc.styleSheets;
return Array.from(sheets).pop();
--but to no avail. Is this possible, what I'm trying to accomplish? Or am I going to have to break this process out into multiple functions?