谷歌网络字体:如何在加载后卸载字体?

8

目前,我可以使用Google的Web字体加载器轻松地加载Web字体:

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

但是,是否有可能后来从 DOM 中卸载字体和添加的元素,以便它们不再在页面上使用?
项目的 Github 文档没有显示任何提供该功能的选项或方法。


5
这是我昨天回答一个问题后,提问者删除了该问题的一篇延迟发表的复制品。这样做是为了保持答案完整并公开可用。 - Etheryte
1个回答

8
您可以简单地使用MutationObserver来跟踪对DOM所做的更改,并在需要时删除添加的元素。
下面是一个简单的示例实现:

(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>


这将是一种在使用数百种不同的谷歌字体时保持性能良好的方法吗? - OMNIA Design and Marketing

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接