使用Javascript为整个会话加载网站字体

Load font for website for the whole session using Javascript

本文关键字:加载 网站 字体 会话 Javascript 使用      更新时间:2023-09-26

我正在制作一个印地语网站,为此我必须使用javascript从谷歌字体加载字体。
我想在开始页上加载整个会话的字体,我应该使用什么javascript代码??
我使用以下代码在每个页面上加载字体:

WebFontConfig = {
google: { families: [ 'Jaldi::devanagari' ] },
active: fontLoaded
};
(function() {
    var wf = document.createElement('script');
    wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
    wf.type = 'text/javascript';
    wf.async = 'true';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(wf, s);
})();

浏览器缓存资源(除非手动禁用了缓存)。这意味着,只要浏览器在其字体缓存中有该字体,添加资源将而不是使浏览器再次下载该字体。它将使用缓存中的字体。(JavaScript文件也是如此,因此webfont.js脚本也将被缓存)。

请注意,您仍然需要让浏览器执行脚本,因此您需要在需要字体的每个页面上添加script标记(就像您正在做的那样)。

tl;dr:你不需要改变任何东西(至少从你的问题中我可以看出)。