To jest to, co stworzyłem dla naszych potrzeb. Jeśli to spełnia twoje potrzeby, po prostu wywołaj funkcję ensureCssFileInclusion (plik do sprawdzenia, wartość boolowska). Będziesz musiał dostosować go do swoich potrzeb, aby upewnić się, że podasz cssFileToCheck, fallbackCssFile w tej funkcji.
/**
* Checks the page for given CSS file name to see if it was already included within page stylesheets.
* If it was, then this function does nothing else. If CSS file was not found among page stylesheets,
* then this function will attempt to load the stylesheet by adding an HTML link tag to the document
* HEAD section. You must also specify whether given cssFileToInclude is a relative path or an absolute path.
*/
ensureCssFileInclusion = function(cssFileToInclude, isRelativePath) {
if (isRelativePath) {
if (!window.location.origin) {
cssFileToInclude = window.location.protocol+"//"+window.location.host + cssFileToInclude;
}
}
var styleSheets = document.styleSheets;
for (var i = 0, max = styleSheets.length; i < max; i++) {
if (styleSheets[i].href == cssFileToInclude) {
return;
}
}
// because no matching stylesheets were found, we will add a new HTML link element to the HEAD section of the page.
var link = document.createElement("link");
link.rel = "stylesheet";
link.href = cssFileToInclude;
document.getElementsByTagName("head")[0].appendChild(link);
};
To może być trudne, ponieważ * myślę * CSS ładuje się asynchronicznie. – Pointy
Nie chcesz, aby JQuery lub inne zasoby były ładowane, ale kod, który udostępniłem poniżej, jest czystym kodem JavaScript i nie ma zależności od jQuery (chyba). Bez używania javascript nie znam żadnego innego sposobu osiągnięcia tego, czego szukasz. O ile oczywiście nie ma jakiejś wersji do specyfikacji w3, w której można określić bibliotekę zastępczą - co, jak sądzę, byłoby bardzo dobrą aktualizacją specyfikacji w przyszłości. – smallworld