How to fallback to local stylesheet (not script) if CDN fails
To handle CSS fallbacks, use the <link>
tag's onerror
attribute. This fires a function to fetch a local stylesheet in case of a CDN failure.
Upon CDN failure, onerror
swiftly switches the href
to point to your local file, ensuring uninterrupted styling. Including this.onerror=null
is vital to prevent multiple fallback attempts if even the local file fails.
onerror—Your Sleek Knight in Shining Armor
Besides replacing href
, you can also dynamically append another stylesheet using JavaScript. This method offers expanded control, enabling multiple level fallbacks or comprehensive error handling.
This carefully placed script hails the local stylesheet to the <head>
element upon detecting a CDN load failure.
The Art of Detecting Successful Load
Another course of action involves validating stylesheet load success by creating a test rule in your stylesheet and verifying if it applies.
In JavaScript:
This method checks for a specific rule from the CDN stylesheet when the page loads. This ensures a false positive is not raised due to stylesheet prefetching.
Roll Back to Alternative Fallback Methods
Swift DOM Reload After CDN Defeat
Should the CDN lose the battle as indicated with .cssRules
or .rules
compatibility checks, dynamically load local resources as reinforcements:
Combat Guide for a Serene User Experience
-
Overcome browser discrepancies: Check fallback behavior across various browsers. Some browsers might show distinct behaviors when executing error handlers.
-
Prepare for consistent network conditions: On occasions, even if network restores quickly, failover might trigger. Equip with strategy by implementing timeout delays or additional verification checks.
Employing Forces like jQuery
With jQuery, you can simplify your dynamic loading code:
Remember, this trick will only work if jQuery itself is being served locally or if you're certain of its availability.
Was this article helpful?