call jQuery function after fonts are loaded.

浪子不回头ぞ 提交于 2019-11-30 14:04:56

One problem with the Google font loader callbacks/events is that if you're using jQuery - you may not want to run your event handler until the DOM is loaded - but you don't want to risk running it before you're sure all fonts are loaded.

Here's my solution for that. Assumptions:

  • You've are using the Google Font loader
  • You want to run something only after all fonts, css and the DOM are loaded
  • You're fine with having jQuery load before the font loader starts (because I'm using $.Callbacks())

This is what I do immediately after the jQuery <script> tag

 var activeCallback = $.Callbacks();

 WebFontConfig = {
     google: { families: ['Open+Sans:400italic,400,300,600:latin'] },
     active: function () { activeCallback.fire(); }
 };

 // ...

And then a standard jQuery ready function

 $(function() 
 {
    // start slide show when all fonts are loaded (need to calculate heights)
    activeCallback.add(function ()
    {
        startSlideshow();
    });

    // other DOM manipulation
 });

The callback will fire whenever the Google font loader is complete - but if the document is not yet completed the event will not be fired until it has (that's the way jQuery Callbacks work).

In order to capture the event, you'll need to use a font loader. Sadly, there isn't a cross-browser way of loading the fonts, so I suggest you try the Google WebFont Loader:

var WebFontConfig = {
  monotype: {  // Fonts.com 
    projectId: 'YourProjectId'
  },
  active: function() {
    // do something
  }
};

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

If you want to control the loading process of @font-faces use WebFont Loader, developed by Google and Typekit.

https://developers.google.com/webfonts/docs/webfont_loader

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!