【问题标题】:How to catch when was loaded my material icons?如何捕捉我的材质图标何时加载?
【发布时间】:2018-06-15 13:02:18
【问题描述】:
我正在使用 Google 的这些图标字体:
https://material.io/icons/
我正在开发一个网络扩展程序,一些网页(如 Github)阻止了我的图标,我正在尝试使用 vanilla js 检查字体是否可用,这里的问题是我不知道什么时候需要确认字体是否已加载。
我正在使用 setTimeOut,但我真的很讨厌这种方法。
我的代码:
function confirmFont(view) {
setTimeout(function(){
if(!document.fonts.check("12px Material-Icons")) {
.....
}
}, 2000);
}
我尝试过准备好文档并加载窗口,但这不起作用,我需要更具体。
【问题讨论】:
标签:
javascript
icons
google-material-icons
【解决方案1】:
如果您已经使用document.fonts,为什么不使用该接口附带的Events?由于每当字体集完成加载时都会触发loadingdone 事件,因此您实际上可以使用事件侦听器来检查您的字体。下面是一个工作示例:
!function() {
// Setting up listener for font checking
var font = "1rem 'Material Icons'";
document.fonts.addEventListener('loadingdone', function(event) {
console.log(`Checking ${font}: ${ document.fonts.check(font)}`);
})
// Loading font
var link = document.createElement('link'),
head = document.getElementsByTagName('head')[0];
link.addEventListener('load', function() {
console.log('Font loaded');
})
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = 'https://fonts.googleapis.com/icon?family=Material+Icons';
head.appendChild(link);
}()
<i class="material-icons md-48">face</i>
【解决方案2】:
我已经通过以下方式解决了这个问题:
document.fonts.ready.then(function () {
if(!document.fonts.check("12px Material-Icons")) {
...
}
});