gpt4 book ai didi

javascript - 如何在谷歌字体加载时显示加载图像?

转载 作者:行者123 更新时间:2023-11-28 02:42:54 25 4
gpt4 key购买 nike

我正在使用谷歌字体 API。在 document.ready 中,我请求了谷歌字体集合,并使用所有可用的字体系列填充选择列表。现在,当用户从选择列表中选择任何字体时,我只需在文档中附加请求所选字体并显示字体预览的链接。但我试图在加载字体进行预览时显示加载图像。我的代码:

    $("#ff").selectmenu({ select: function () {
var img = $("<img />").attr("src", "/images/load.gif");
$(".preview").append(img);
$('body').append("<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=" + escape($(this).val()) + "' type='text/css' media='all' />");
$(".preview").css({ fontFamily: $(this).val() });
$(img).remove();
}
});

但是加载图像没有显示,因为可能是链接标记正在异步请求字体。如何在字体完全加载之前显示加载图像?

最佳答案

这是 csuwldcat 提供的另一个答案在另一篇文章中。

javascript: capturing load event on LINK

Here's what is, in my opinion, a better solution for this issue that uses the IMG tag and its onerror event. This method will do the job without looping, doing contorted style observance, or loading files in iframes, etc. This solution fires correctly when the file is loads, and right away if the file is already cached (which is ironically better than how most DOM load events handle cached assets). Here's a post on my blog that explains the method - Back Alley Coder post - I just got tired of this not having a legit solution, enjoy!

var loadCSS = function(url, callback){
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = url;

document.getElementsByTagName('head')[0].appendChild(link);

var img = document.createElement('img');
img.onerror = function(){
if(callback) callback(link);
}
img.src = url;

}

请对他的回答进行投票,确保他得到认可。

关于javascript - 如何在谷歌字体加载时显示加载图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12399362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com