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

标签 javascript jquery

我正在使用谷歌字体 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/

相关文章:

javascript - AngularJS 1.3 - 错误 : error:modulerr Module Error (using ng-view, $routeProvider)

javascript - 在浏览器窗口调整大小时保持纵横比?

java - 检测扬声器是否已插入?

javascript - 将使用 D3js 创建的 SVG 转换为 PNG

javascript - 如何使用 list.js 选择下拉选项来对列表项进行排序

javascript - 为什么这个 jQuery 代码片段在 IE8 中不能像在 Firefox 或 Chrome 中那样工作(包括现场演示)?

javascript - 我希望在 Chrome 客户端存储大量数据,我有哪些选择?

javascript - 在 svelte 中使用后退按钮事件监听器

javascript - jquery 函数输入单选 onchange

php - 在 jQuery ajax 数据字符串中使用的字符串值的序列化函数