Google Webfonts: how to unload fonts after loading them?
Asked Answered
W

1

8

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.

Worship answered 27/2, 2015 at 13:43 Comment(1)
This is a posthumous replica of a question I answered yesterday that the asker deleted after receiving an answer. This serves to keep the answer intact and publicly available.Worship
W
8

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>
Worship answered 27/2, 2015 at 13:43 Comment(1)
So this would be a way to keep performance good while using 100's of different Google fonts?Schoonmaker

© 2022 - 2024 — McMap. All rights reserved.