javascriptwebfontsgoogle-webfontswebfont-loader

Google Webfonts: how to unload fonts after loading them?


Currently I can load a web font very easily using Google's Web Font loader:

WebFont.load({
    google: {
        families: ['Bree Serif']
    }
});

However, is it possible to later unload the fonts and added elements from the DOM so they're no longer used on the page?
The documentation on the project's Github doesn't show any options or methods that offer the functionality.


Solution

  • You can simply use a MutationObserver to keep track of the changes made to the DOM and remove the added elements when you so desire.
    Below is a simple sample implementation:

    (function() {
      "use strict";
      var addedNodes = [];
      var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
          Array.prototype.forEach.call(mutation.addedNodes, function(node) {
            addedNodes.push(node);
          });
        });
        observer.disconnect();
      });
      loader.addEventListener('click', function() {
        observer.observe(document, {
          childList: true,
          subtree: true,
          addedNodes: true
        });
        //Two loads simply to demonstrate that's not a problem
        WebFont.load({
          google: {
            families: ['Bree Serif']
          }
        });
        WebFont.load({
          google: {
            families: ['Indie Flower']
          }
        });
        loader.disabled = true;
        remover.disabled = false;
      });
    
      remover.addEventListener('click', function() {
        addedNodes.forEach(function(node) {
          node.remove();
        });
        addedNodes = [];
        loader.disabled = false;
        remover.disabled = true;
      });
    }());
    body {
      text-align: center;
      background: aliceblue;
    }
    h1 {
      font-family: 'Indie Flower';
      font-size: 3em;
      color: cadetblue;
    }
    p {
      font-family: 'Bree Serif';
      color: crimson;
    }
    input[disabled] {
      display: none;
    }
    <script src="//ajax.googleapis.com/ajax/libs/webfont/1.5.10/webfont.js"></script>
    <input id="loader" type="button" value="Click to load webfonts" />
    <input id="remover" type="button" value="Remove loaded webfonts" disabled="true" />
    <h1>Chapter 1</h1>
    <p>Grumpy wizards make toxic brew for the evil Queen and Jack.</p>