3

Is there a generic solution for loading a local backup CSS file when CDN is down?

<link rel="stylesheet" href="//somecdn.com/somefile.css"/>
<!-- load a local file here if needed -->

I have 5 such CSS files from different CDNs, and the order of loading matters.

The solutions I came across so far are less than satisfactory:

  • create a dummy div and use it to check some property that should have been loaded
  • check document.styleSheets[0].cssRules.length -- this is cross-site access and not allowed by some browsers
Victor Lyuboslavsky
  • 9,882
  • 25
  • 87
  • 134

2 Answers2

0

The div attribute detection works as the first step. Pick something that works reliably. For example, height and visibility might work well.

Based on the detection result you can decide to load a local css dynamically:

    csl=document.createElement('link');
    csl.setAttribute('rel','stylesheet');
    csl.setAttribute('type','text/css');
    csl.setAttribute('href','mylocalcss.css');
    document.getElementsByTagName("head").item(0).appendChild(csl);
Schien
  • 3,855
  • 1
  • 16
  • 29
0

If CDN is not reliable, then do not use them.

There is no easy way to load a backup CSS like there is for JS files. Switch to always load local CSS, but continue to use CDN for JS (with a local backup).

Community
  • 1
  • 1
Victor Lyuboslavsky
  • 9,882
  • 25
  • 87
  • 134