I'm loading the Bootstrap CSS on my page from the CDN bootstrapcdn.com
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
How can I test if the stylesheet was loaded, and if not provide a local fallback?
I do not want to wait for jQuery or other libraries to load before doing the test; I want all CSS to be loaded on the page first.
CDNs don't fail very often but when they do, it can be spectacular. There are many similarities between this outage and an issue with rival Cloudflare last year. Cloudflare's problems arose because -- in simple terms -- the company's engineers tried to re-route internet traffic and everything exploded.
asp-fallback-test-value - The value of the CSS property that the test element should have, if the linked stylesheet didn't load correctly. asp-fallback-href - The URL of the file to load if the test fails.
To your question on Best Practices, there are a lot of very good reasons to use a CDN in a production environment: It increases the parallelism available. It increases the chance that there will be a cache-hit. It ensures that the payload will be as small as possible.
This is what I have created for our needs. If this meets your needs, simply call the function ensureCssFileInclusion(file to check, boolean value). You will have to adjust it for your needs to make sure that you provide the cssFileToCheck, fallbackCssFile in this function.
/**
* 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);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With