Gaurav
Gaurav

Reputation: 8487

How to show a loading image while google font loading?

I am using google fonts api. In document.ready i requested the google fonts collection and populate the select list with all available font-families. Now when user select any font from selectlist i just append the link in the document which request the selected font and show the font-preview. But i am trying to show the loading image while the font is loading for preview. My code :

    $("#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();
    }
    });

But the loading image is not showing because may be the link tag is requesting the font asynchronously. How can i show the loading image until the font is fully loaded ?

Upvotes: 1

Views: 362

Answers (1)

Joe Mills
Joe Mills

Reputation: 1619

Here is another answer provided by csuwldcat on another post.

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; 

}

Please vote up his response, ensuring he gets credit.

Upvotes: 1

Related Questions