使用 webfontloader 优化加载字体在网页中的显示体验

使用方式:

WebFont.load({
  google: {
    families: ['Roboto:300,400,500,700', 'Open Sans']
  },
  custom: {
    families: ['My Font'],
    urls: ['path/to/myfont.css']
  },
  active: function() {
    // 字体加载成功后执行的回调函数
  },
  inactive: function() {
    // 字体加载失败后执行的回调函数
  }
});

一个项目中的使用示例:

将样式创建好,然后使用webfontloader进行监听加载,要是加载完成,再将样式添加进去。
当然也可以将三种字体分开,这样就不捆绑在一起了。

<script>
        //最后加载字体,防止网页加载速度
        // 创建一个新的<style>标签
        var style = document.createElement('style');
        // 将字体文件链接放在<style>标签中
        style.textContent = `
            <?php if(!empty(_g('title_font'))){?>
            @font-face {
                font-family: 'indexTitleFont';
                src: url('<?php echo _g('title_font'); ?>') format('woff');
            }
            <?php }?>

            <?php if(!empty(_g('article_font'))){?>
            @font-face {
                font-family: 'article_font';
                src: url('<?php echo _g('article_font'); ?>') format('woff');
            }
            <?php }?>

            <?php if(!empty(_g('saying_font'))){?>
            @font-face {
                font-family: 'saying_font';
                src: url('<?php echo _g('saying_font'); ?>') format('woff');
            }
            <?php }?>
        `;
        WebFont.load({
            custom: {
                families: ['indexTitleFont', 'article_font','saying_font']
            },
            active: function() {
                // 字体加载完成后执行的操作
                document.head.appendChild(style);
            },
            inactive: function() {
                // 字体加载失败时执行的操作
                document.head.appendChild(style);
            }
        });
    </script>
请登录后发表评论

    没有回复内容