thierry-b
12/16/2014 - 8:38 AM

Loading CSS and Webfonts async with fallback IE10 (sessionStorage)

Loading CSS and Webfonts async with fallback IE10 (sessionStorage)

  (function(){
      var storage;
      var fail;
      var uid;
      try {
        uid = new Date;
        (storage = window.localStorage).setItem(uid, uid);
        fail = storage.getItem(uid) != uid;
        storage.removeItem(uid);
        fail && (storage = false);
      } catch (exception) {
        try {
          (storage = window.sessionStorage).setItem(uid, uid);
          fail = storage.getItem(uid) != uid;
          storage.removeItem(uid);
          fail && (storage = false);
        } catch (exception) {}
      }

      function addFont() {
          var style = document.createElement('style');
          style.rel = 'stylesheet';
          document.head.appendChild(style);
          style.textContent = storage.fonts;
      }

      function addCSS() {
          var style = document.createElement('style');
          style.rel = 'stylesheet';
          document.head.appendChild(style);
          style.textContent = storage.css;
      }

      try {
          if (storage.fonts && storage.css) {
              // The font & css is in localStorage
              addFont();
              addCSS();
          } else {
              var fontRequest = new XMLHttpRequest();
              fontRequest.open('GET', '<?php print base_path() . path_to_theme(); ?>/css/fonts.css', true);
              fontRequest.onload = function() {
                  if (fontRequest.status >= 200 && fontRequest.status < 400) {
                      // We save the file in localStorage
                      storage.fonts = fontRequest.responseText;
                      addFont();
                  }
              }
              fontRequest.send();

              var cssRequest = new XMLHttpRequest();
              cssRequest.open('GET', '<?php print base_path() . path_to_theme(); ?>/css/build/style.min.css', true);
              cssRequest.onload = function() {
                  if (cssRequest.status >= 200 && cssRequest.status < 400) {
                      // We save the file in localStorage
                      storage.css = cssRequest.responseText.replace(/\.\.\//g, '<?php print base_path() . path_to_theme(); ?>/');
                      addCSS();
                  }
              }
              cssRequest.send();
          }
      } catch(ex) {
          // maybe load the font synchronously for woff-capable browsers
          // to avoid blinking on every request when localStorage is not available
      }
  }());