<!-- Check out head settings by clicking the cog icon next to the HTML window -->

<body class="no-js">
  <p>
    <button onClick="loadFontCSS()">
  Load Font CSS - initiate font file download
    </button></p>
  
  <p>
    Font: <span id="js-font-status">not loaded</span>
  </p>
  
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus pulvinar nulla. Proin vitae ex vitae eros ultricies placerat. Vivamus consectetur ultrices vulputate. Curabitur sit amet scelerisque tortor, nec eleifend dolor. Vestibulum justo arcu, volutpat vel fermentum et, tempus vulputate metus.</p>
 
  
 
  
  <script>
    /* If JavaScript is not available, 
     * you can use .no-js class to apply
     * web font styles.
     *
     * If JS is available, 
     * this class will be removed.    
     */
    document.getElementsByTagName("body")[0].classList.remove("no-js");
  </script>
  
</body>
body {
  max-width: 568px;
  margin: 0 auto;
  padding: 1em;
  font-family: "Merriweather", Georgia, serif;
  font-size: 24px;
  line-height: 1.5;
}
let interval = null;

function fontLoadListener() {
  var hasLoaded = false
      /* 
       * If anything goes wrong with the font loading API, 
       * just change styles to the web font without handling FOUT 
       */
      try {
        hasLoaded = document.fonts.check('12px "Merriweather"')
      } catch (error) {
        console.info(`document.fonts API error: ${error}`)
        fontLoadedSuccess();
        return
      }
  
  if(hasLoaded) {
    fontLoadedSuccess();
  }
}

function fontLoadedSuccess() {
  if(interval) {
    clearInterval(interval);
  }
  
  document.getElementById("js-font-status").innerHTML = "finished loading";
  document.getElementsByTagName("body")[0].classList.add("wf-merriweather--loaded");
}

/*
 * We'll start the interval on button click so 
 * we don't run it all the time in the background 
 * when no loading is happening. 
 * You can uncomment the line on your project.
 *
 * interval = setInterval(fontLoadListener, 500)
 */

/* Button click code - not relevant to the example */

function loadFontCSS() {
  interval = setInterval(fontLoadListener, 500)
  var link = document.createElement("link");
  link.rel = "stylesheet";
  link.href="https://fonts.googleapis.com/css2?family=Merriweather&display=swap";
  
  document.getElementsByTagName("head")[0].appendChild(link);
}

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.