Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Support for stylesheet load events and providing font fallbacks if CDN goes down

  • This topic is empty.
Viewing 1 post (of 1 total)
  • Author
    Posts
  • #159187
    cmscss
    Participant

    Hi There,

    Does anyone know which browsers besides Firefox support stylesheet load events?

    See here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#Stylesheet_load_events

    I’ve spent many hours trying to provide a local server-based fallback for fonts incase a CDN goes down. This is something a designer would want to do but it seems the browser vendors disagree, hence the javascript shenanigans below.

    Any help on browser support for the beautifully simple example in the MDN link above (which I got working in literally 1 minute) or with the javascript below would be very much appreciated – for the life of me I can’t figure out how to get the if statement to check if the stylesheets have loaded.

    console.log(cdnFont); always returns false (yes, I’m a designer with little to no JS skills) – sorry if this is easy.

    Cheers

    Ben

    BTW, I’m trying to accomplish this using javascript because jQuery won’t have loaded by this point (plus, I’m not sure this project will use jQuery).

    <!-- initial load via cdn without javascript -->
    <link href="//fonts.googleapis.com/css?family=Flamenco" rel="stylesheet" type="text/css">
    <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet" type="text/css">
    
    <script>
      // check that fonts loaded via CDN
      function fontLoaded() {
        var cdnFont = false;
        for (var i = 0; i < document.styleSheets.length; i++) {
          var font = document.styleSheets[i];
          if (font['href'] == "//fonts.googleapis.com/css?family=Flamenco" && "//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css") {
            cdnFont = true;
          }
        };
    
        console.log(cdnFont);
        return cdnFont;
      }
    
      // if fonts didn't load via CDN, load from local assets directory
      if (!fontLoaded()) {
        var font = document.createElement("link");
        font.rel = "stylesheet";
        font.href = "/assets/fonts/local-fonts.css";
        document.getElementsByTagName("head")[0].appendChild(font);
      }
    </script>
    
Viewing 1 post (of 1 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.