Giter Site home page Giter Site logo

webfontloader's Introduction

Web Font Loader

Web Font Loader gives you added control when using linked fonts via @font-face. It provides a common interface to loading fonts regardless of the source, then adds a standard set of events you may use to control the loading experience. The Web Font Loader is able to load fonts from Google Fonts, Typekit, Fonts.com, and Fontdeck, as well as self-hosted web fonts. It is co-developed by Google and Typekit.

Build Status

Contents

Get Started

To use the Web Font Loader library, just include it in your page and tell it which fonts to load. For example, you could load fonts from Google Fonts using the Web Font Loader hosted on Google Hosted Libraries using the following code.

<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
<script>
  WebFont.load({
    google: {
      families: ['Droid Sans', 'Droid Serif']
    }
  });
</script>

Alternatively, you can link to the latest 1.x version of the Web Font Loader by using https://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js as the script source. Note that the version in this url is less specific. It will always load the latest 1.x version, but it also has a shorter cache time to ensure that your page gets updates in a timely manner. For performance reasons, we recommend using an explicit version number (such as 1.6.26) in urls when using the Web Font Loader in production. You can manually update the Web Font Loader version number in the url when you want to adopt a new version.

Web Font Loader is also available on the jsDelivr & CDNJS CDNs.

It is also possible to use the Web Font Loader asynchronously. For example, to load Typekit fonts asynchronously, you could use the following code.

<script>
   WebFontConfig = {
      typekit: { id: 'xxxxxx' }
   };

   (function(d) {
      var wf = d.createElement('script'), s = d.scripts[0];
      wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js';
      wf.async = true;
      s.parentNode.insertBefore(wf, s);
   })(document);
</script>

Using the Web Font Loader asynchronously avoids blocking your page while loading the JavaScript. Be aware that if the script is used asynchronously, the rest of the page might render before the Web Font Loader is loaded and executed, which can cause a Flash of Unstyled Text (FOUT).

The FOUT can be more easily avoided when loading the Web Font Loader synchronously, as it will automatically set the wf-loading class on the HTML element as soon as Webfont.load has been called. The browser will wait for the script to load before continuing to load the rest of the content, FOUT is avoided.

Web Font Loader is also available on npm as a CommonJS module. Just npm install webfontloader and then require it in your code.

  var WebFont = require('webfontloader');

  WebFont.load({
    google: {
      families: ['Droid Sans', 'Droid Serif']
    }
  });

Configuration

The Web Font Loader configuration is defined by a global variable named WebFontConfig, or passed directly to the WebFont.load method. It defines which fonts to load from each web font provider and gives you the option to specify callbacks for certain events. When using the asynchronous approach, you must define the global variable WebFontConfig before the code that loads the Web Font Loader (as in the example above).

Events

Web Font Loader provides an event system that developers can hook into. It gives you notifications of the font loading sequence in both CSS and JavaScript.

  • loading - This event is triggered when all fonts have been requested.
  • active - This event is triggered when the fonts have rendered.
  • inactive - This event is triggered when the browser does not support linked fonts or if none of the fonts could be loaded.
  • fontloading - This event is triggered once for each font that's loaded.
  • fontactive - This event is triggered once for each font that renders.
  • fontinactive - This event is triggered if the font can't be loaded.

CSS events are implemented as classes on the html element. The following classes are set on the html element:

.wf-loading
.wf-active
.wf-inactive
.wf-<familyname>-<fvd>-loading
.wf-<familyname>-<fvd>-active
.wf-<familyname>-<fvd>-inactive

The <familyname> placeholder will be replaced by a sanitized version of the name of each font family. Spaces and underscores are removed from the name, and all characters are converted to lower case. For example, Droid Sans becomes droidsans. The <fvd> placeholder is a Font Variation Description. Put simply, it's a shorthand for describing the style and weight of a particular font. Here are a few examples:

/* n4 */
@font-face { font-style: normal; font-weight: normal; }

/* i7 */
@font-face { font-style: italic; font-weight: bold; }

Keep in mind that font-weight: normal maps to font-weight: 400 and font-weight: bold maps to font-weight: 700. If no style/weight is specified, the default n4 (font-style: normal; font-weight: normal;) will be used.

If fonts are loaded multiple times on a single page, the CSS classes continue to update to reflect the current state of the page. The global wf-loading class is applied whenever fonts are being requested (even if other fonts are already active or inactive). The wf-inactive class is applied only if none of the fonts on the page have rendered. Otherwise, the wf-active class is applied (even if some fonts are inactive).

JavaScript events are implemented as callback functions on the WebFontConfig configuration object.

WebFontConfig = {
  loading: function() {},
  active: function() {},
  inactive: function() {},
  fontloading: function(familyName, fvd) {},
  fontactive: function(familyName, fvd) {},
  fontinactive: function(familyName, fvd) {}
};

The fontloading, fontactive and fontinactive callbacks are passed the family name and font variation description of the font that concerns the event.

It is possible to disable setting classes on the HTML element by setting the classes configuration parameter to false (defaults to true).

WebFontConfig = {
  classes: false
};

You can also disable font events (callbacks) by setting the events parameter to false (defaults to true).

WebFontConfig = {
  events: false
};

If both events and classes are disabled, the Web Font Loader does not perform font watching and only acts as a way to insert @font-face rules in the document.

Timeouts

Since the Internet is not 100% reliable, it's possible that a font will fail to load. The fontinactive event will be triggered after 5 seconds if the font fails to render. If at least one font successfully renders, the active event will be triggered, else the inactive event will be triggered.

You can change the default timeout by using the timeout option on the WebFontConfig object.

WebFontConfig = {
  google: {
    families: ['Droid Sans']
  },
  timeout: 2000 // Set the timeout to two seconds
};

The timeout value should be in milliseconds, and defaults to 3000 milliseconds (3 seconds) if not supplied.

Iframes

Usually, it's easiest to include a copy of Web Font Loader in every window where fonts are needed, so that each window manages its own fonts. However, if you need to have a single window manage fonts for multiple same-origin child windows or iframes that are built up using JavaScript, Web Font Loader supports that as well. Just use the optional context configuration option and give it a reference to the target window for loading:

WebFontConfig = {
  google: {
    families: ['Droid Sans']
  },
  context: frames['my-child']
};

This is an advanced configuration option that isn't needed for most use cases.

Modules

Web Font Loader provides a module system so that any web font provider can contribute code that allows their fonts to be loaded. This makes it possible to use multiple web font providers at the same time. The specifics of each provider currently supported by the library are documented here.

Adobe Edge Web Fonts

When using Adobe Edge Web Fonts, you can use the typekit module by passing in a catenated list of fonts in the id parameter and set the api parameter to point to the Edge Web Fonts URL.

WebFontConfig = {
  typekit: {
    id: 'adamina;advent-pro',
    api: '//use.edgefonts.net'
  }
};

Custom

To load fonts from any external stylesheet, use the custom module. Here you'll need to specify the font family names you're trying to load, and optionally the url of the stylesheet that provides the @font-face declarations for those fonts.

You can specify a specific font variation or set of variations to load and watch by appending the variations separated by commas to the family name separated by a colon. Variations are specified using FVD notation.

WebFontConfig = {
  custom: {
    families: ['My Font', 'My Other Font:n4,i4,n7'],
    urls: ['/fonts.css']
  }
};

In this example, the fonts.css file might look something like this:

@font-face {
  font-family: 'My Font';
  src: ...;
}
@font-face {
  font-family: 'My Other Font';
  font-style: normal;
  font-weight: normal; /* or 400 */
  src: ...;
}
@font-face {
  font-family: 'My Other Font';
  font-style: italic;
  font-weight: normal; /* or 400 */
  src: ...;
}
@font-face {
  font-family: 'My Other Font';
  font-style: normal;
  font-weight: bold; /* or 700 */
  src: ...;
}

If your fonts are already included in another stylesheet you can also leave out the urls array and just specify font family names to start font loading. As long as the names match those that are declared in the families array, the proper loading classes will be applied to the html element.

<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.5.10/webfont.js"></script>
<script>
  WebFont.load({
    custom: {
      families: ['My Font']
    }
  });
</script>

<style type="text/css">
  @font-face {
    font-family:"My Font";
    src:url("assets/fonts/my_font.woff") format("woff");
  }
</style>

The custom module also supports customizing the test strings that are used to determine whether or not a font has loaded. This can be used to load fonts with custom subsets or glyphs in the private use unicode area.

WebFontConfig = {
  custom: {
    families: ['My Font'],
    testStrings: {
      'My Font': '\uE003\uE005'
    }
  }
};

Tests strings should be specified on a per font basis and contain at least one character. If not specified the default test string (BESbswy) is used.

Fontdeck

To use the Fontdeck module, specify the ID of your website. You can find this ID on the website page within your account settings.

WebFontConfig = {
  fontdeck: {
    id: 'xxxxx'
  }
};

Fonts.com

When using Fonts.com web fonts specify your Project ID.

WebFontConfig = {
  monotype: {
    projectId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
    version: 12345, // (optional, flushes the CDN cache)
    loadAllFonts: true //(optional, loads all project fonts)
  }
};

The Fonts.com module has an optional version option which acts as a cache-buster, optional loadAllFonts loads all project fonts. By default, Fonts.com module loads only fonts used on the page.

Google

Using Google's Font API, name the font families you'd like to load. You can use the same syntax as in the Font API to specify styles. Please note that the Google module does not support the FVD syntax that is used in the custom module.

WebFontConfig = {
  google: {
    families: ['Droid Sans', 'Droid Serif:bold']
  }
};

Sometimes the font you requested doesn't come in the default weight (e.g. 400) and you need to explicitly request the variation you want for font events to work (e.g. 300, 700, etc.):

WebFontConfig = {
  google: {
    families: ['Open Sans Condensed:300,700']
  }
};

If you need to specify character subsets other than the default (e.g.: greek script in addition to latin), you must append the subset string to the requested family string after a colon. The subset string should follow the Google documentation (subset names separated by commas):

WebFontConfig = {
  google: {
    families: ['Open Sans Condensed:300,700:latin,greek']
  }
};

You can also supply the text parameter to perform character subsetting:

WebFontConfig = {
  google: {
    families: ['Droid Sans', 'Droid Serif'],
    text: 'abcdefghijklmnopqrstuvwxyz!'
  }
};

The text subsetting functionality is only available for the Google module.

Typekit

When using Typekit, specify the Kit to retrieve by its ID. You can find the Kit ID within Typekit's Kit Editor interface.

WebFontConfig = {
  typekit: {
    id: 'xxxxxx'
  }
};

FYI: Typekit's own JavaScript is built using the Web Font Loader library and already provides all of the same font event functionality. If you're using Typekit, you should use their embed codes directly unless you also need to load web fonts from other providers on the same page.

Browser Support

Every web browser has varying levels of support for fonts linked via @font-face. Web Font Loader determines support for web fonts is using the browser's user agent string. The user agent string may claim to support a web font format when it in fact does not. This is especially noticeable on mobile browsers with a "Desktop" mode, which usually identify as Chrome on Linux. In this case a web font provider may decide to send WOFF fonts to the device because the real desktop Chrome supports it, while the mobile browser does not. The Web Font Loader is not designed to handle these cases and it defaults to believing what's in the user agent string. Web font providers can build on top of the basic Web Font Loader functionality to handle these special cases individually.

If Web Font Loader determines that the current browser does not support @font-face, the inactive event will be triggered.

When loading fonts from multiple providers, each provider may or may not support a given browser. If Web Font Loader determines that the current browser can support @font-face, and at least one provider is able to serve fonts, the fonts from that provider will be loaded. When finished, the active event will be triggered.

For fonts loaded from supported providers, the fontactive event will be triggered. For fonts loaded from a provider that does not support the current browser, the fontinactive event will be triggered.

For example:

WebFontConfig = {
  providerA: 'Family1',
  providerB: 'Family2'
};

If providerA can serve fonts to a browser, but providerB cannot, The fontinactive event will be triggered for Family2. The fontactive event will be triggered for Family1 once it loads, as will the active event.

Copyright and License

Web Font Loader Copyright (c) 2010-2017 Adobe Systems Incorporated, Google Incorporated.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

webfontloader's People

Contributors

ahume avatar bee525 avatar bnjmnt4n avatar bradoyler avatar bramstein avatar davidql avatar dgreisen avatar durchanek avatar febley avatar felthy avatar jastrzebowski avatar jeremiele avatar nripendra avatar omo avatar p4121 avatar parterburn avatar paulirish avatar peterdavehello avatar phawk avatar prayagverma avatar pzula avatar ramghaju avatar raziel avatar rondevera avatar ryanwolf avatar sirbrillig avatar tombyrer avatar venkatyetrintala-zz avatar vitalyvolkov avatar zackify avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

webfontloader's Issues

self-hosted font variations

In a stylesheet I have

@font-face {
    font-family: 'myfont';
    font-weight: bold;
    font-style: normal;
    src: url('../fonts/myfont-Bold-webfont.eot');
    src: url('../fonts/myfont-Bold-webfont.eot?iefix') format('eot'),
         url('../fonts/myfont-Bold-webfont.woff') format('woff'),
         url('../fonts/myfont-Bold-webfont.ttf') format('truetype'),
         url('../fonts/myfont-Bold-webfont.svgz#webfontfJXKJAfV') format('svg'),
         url('../fonts/myfont-Bold-webfont.svg#webfontfJXKJAfV') format('svg');
}
@font-face {
    font-family: 'myfont';
    font-weight: normal;
    font-style: normal;
    src: url('../fonts/myfont-Book-webfont.eot');
    src: url('../fonts/myfont-Book-webfont.eot?iefix') format('eot'),
         url('../fonts/myfont-Book-webfont.woff') format('woff'),
         url('../fonts/myfont-Book-webfont.ttf') format('truetype'),
         url('../fonts/myfont-Book-webfont.svgz#webfont3yluhAu4') format('svg'),
         url('../fonts/myfont-Book-webfont.svg#webfont3yluhAu4') format('svg');
}

and in a script, I have

WebFont.load({
    custom: {
        families: ['myfont:r,b']
    }
});

Yet, for some reasons, the resulting class gets to be wf-myfontrb-n4-active,
instead of wf-myfont-n4-active + wf-myfont-n7-active

Or any other variation :
['myfont:regular,bold']gives me in the end wf-myfontregularbold-n4-active,
['myfont:normal,bold']gives me in the end wf-myfontnormalbold-n4-active,
['myfont:400,700']gives me wf-myfont400700-n4-active,
etc

As soon as I use non-self hosted fonts, everything's fine, though. Have I missed something ?

"rake demo" gives java.lang.UnsupportedClassVersionError: Bad version number in .class file

I'm using OSX 10.5 with bundled Java 1.5.0_22 and I get this error when trying to "rake demo".

Exception in thread "main" java.lang.UnsupportedClassVersionError: Bad version number in .class file
  at java.lang.ClassLoader.defineClass1(Native Method)
  at java.lang.ClassLoader.defineClass(ClassLoader.java:676)
  at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
  at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
  at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
  at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:317)
  at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:280)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
  at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:375)
bin/webfontloader-demos:22:in `read': No such file or directory - target/webfont.js (Errno::ENOENT)
  from bin/webfontloader-demos:22
  from ~/.rvm/rubies/ruby-1.8.6-p383/lib/ruby/1.8/optparse.rb:1265:in `call'
  from ~/.rvm/rubies/ruby-1.8.6-p383/lib/ruby/1.8/optparse.rb:1265:in `parse_in_order'
  from ~/.rvm/rubies/ruby-1.8.6-p383/lib/ruby/1.8/optparse.rb:1252:in `catch'
  from ~/.rvm/rubies/ruby-1.8.6-p383/lib/ruby/1.8/optparse.rb:1252:in `parse_in_order'
  from ~/.rvm/rubies/ruby-1.8.6-p383/lib/ruby/1.8/optparse.rb:1246:in `order!'
  from ~/.rvm/rubies/ruby-1.8.6-p383/lib/ruby/1.8/optparse.rb:1337:in `permute!'
  from ~/.rvm/rubies/ruby-1.8.6-p383/lib/ruby/1.8/optparse.rb:1358:in `parse!'
  from ~/.rvm/gems/ruby-1.8.6-p383/gems/vegas-0.1.6/lib/vegas/runner.rb:278:in `define_options'
  from ~/.rvm/gems/ruby-1.8.6-p383/gems/vegas-0.1.6/lib/vegas/runner.rb:39:in `initialize'
  from bin/webfontloader-demos:20:in `new'
  from bin/webfontloader-demos:20

JS error loading fonts in hidden iframe (firefox)

Problem occurs when the iframe uses the webfont loader and is hidden.
Only happens in Firefox (did not yet test IE)

error is this.document_.defaultView.getComputedStyle(b, null) is null

see example here: http://dev.gimme.io/test/fontembed.html
my example uses fonts.com fonts but I reported it to them and they tested and the problem is not on their end.

I believe there was a similar bug in jQuery a while back

SSL support in Typekit module

It would be useful to have a Webfont Loader configuration option for the TypeKit module to specify whether to use SSL or not. I know SSL isn't supported in all TypeKit subscriptions, but for those with support, perhaps an "auto" setting that would toggle between http:// and https:// support depending on the page (ie document.location.protocol), a "force" or "true" setting that would operate similarly to the TypeKit editor SSL toggle (making all requests over SSL), and a "default" or "false" setting that would operate as it does now, not using SSL.

Browsing through the code, I found the API configuration setting, and ended up using:

api: "http" + ("https:" == document.location.protocol ? "s" : "") + "://use.typekit.com"

But that isn't the most obvious or well documented solution for many non-programmers. Short of adding support for a setting, it might be worth publicizing the api setting for situations like this.

Add support for documentMode detection with UserAgent.

I am proposing we add a new method to the UserAgent object, getDocumentMode, which is used to expose the document mode that IE8+ browsers are using to render the page. This will be required in the future to determine whether IE9 can show WOFF files, as it only does so when the documentMode == 9.

The code has been implemented in this branch comments are welcome.

`active` event on Firefox trigger too early

Hi, it seems like the active event occurs too early on Firefox (v17). The event trigger before the fonts are actually rendered on the page.

I haven't been able to reproduce this bug with all settings. But when using multiple custom fonts this seems to happen everytime.

Is this a known issue?

Docs should show google jsapi included

I believe the following line is necessary to get the examples in the README working:

<script src="https://www.google.com/jsapi"> .... so I think it should be explicitly included in the example.

webfont.FontApiUrlBuilder trying to load fonts locally when using local protocol

Tried to fork the project and add the conditional to make this work locally, but it's been trying to create the fork for hours. Basically, in fontapiurlbuilder.js the protocol is defaulting to whatever the document's protocol is, so when working with a local static file, you never access the font file. Instead, if you check the protocol to see if it's not http: or https: and prepend the url string, it works locally. Example replacement code:

webfont.FontApiUrlBuilder = function(apiUrl) {
  this.apiUrl_ = apiUrl || webfont.FontApiUrlBuilder.DEFAULT_API_URL;
  var protocol = window.location.protocol;
  if (protocol != "http:" && protocol != "https:") {
    this.apiUrl_ = "http:" + this.apiUrl_;
  }
  this.fontFamilies_ = null;
};

Easier way to namespace if packaging as part of 3rd party widget

My branch/fork

I make a 3rd party JS plugin that will be bundling the font loader and i can't afford to collide with window['WebFont'], especially if the host page is using their own version of it.

I did a very small bit of clean-up and made things a little more DRY when it comes to the global object.

It's now possible to do something like this in initialize.js:

// Name of the global object.
var globalName = 'WebFont';

// Provide an instance of WebFont in the global namespace.
var globalNamespaceObject = window['MyPluginNamespace'][globalName] = (function() { /* ... */})();

And if I compile or simply make debug output, I have the WebFont object at window.MyPluginNamespace.WebFont which is very handy. This has another nice side effect of slightly smaller compiled output.

'Active' event triggers when resource is downloaded, but sometimes before it is applied in the CSS

I have a simple function that console logs the height of the document element when the Web font has loaded, using the 'active' event.

active: function () { console.log(document.height); }

Now, the height of the document changes as the Web fonts are loaded. I need to capture the height of the document with the Web fonts once they have loaded. However, very rarely I notice the active event triggers before the fonts have been applied to the document, which means I get an incorrect height. To test this, I added a setTimeout to my active event:

active: function () {
    console.log(document.height); 
    setTimeout(function () { console.log(document.height); }, 1000);
}

Most of the time I will get two identical heights appear in my console, for example 500 and 500. However, if I clear the cache and refresh the page (using Safari, hold shift and press the reload button), sometimes these heights are different. For example, 450 versus 500. This must mean that the 450 height is actually the height of the document before the fonts are applied in the CSS, despite the fact that the active event is being triggered.

Like I say, this only occurs very rarely, and it happens more often when the page is loaded with a clear cache. With a clear cache, this happens for about 1/20 refreshes.

And, it's driving me crazy!

FEATURE REQUEST {Adobe Edge Fonts }

I am not sure if this is already possible, but I was hoping to find a way to use the loader with the newly added Adobe Edge Fonts, http://www.edgefonts.com

They are usually added via js, like this: <script src="http://use.edgefonts.net/aguafina-script:n4.js"></script>

I tried using the 'Custom' command but my font does not seem to be loading that way. Any ideas on how to work this out ?

Thanks in advance.

support for text parameter

Web Fonts supports text= to only load certain characters, which can greatly reduce download size, but WebFont Loader doesn't! Or if it does, then it's not documented. Please add support or document it. Thanks!

Problem in IE8

i have tried with the google sample code. this is not working in IE8.
check here http://www.pro-questions.com/test/fonts1.php
the css as given

<style type="text/css"> .wf-inactive p { font-family: serif } .wf-active p { font-family: 'Tangerine', serif } .wf-inactive h1 { font-family: serif; font-size: 16px } .wf-active h1 { font-family: 'Cantarell', serif; font-size: 16px } </style>

then i change the css as
<style type="text/css">
p {
font-family: 'Tangerine', serif
}
h1 {
font-family: 'Cantarell', serif;
font-size: 16px
}
</style>
then it works on IE8
check here http://www.pro-questions.com/test/fonts2.php
that means
wf-inactive and wf-active is not working in IE8

custom font loader doesn't handle font variations

Hello,

I initially mentioned this problem on #76, but I didn't know exactly what my problem was, so now I'm creating this bug so I don't hijack that issue.

I cannot load font variations with the custom font loader. It is apparently not parsing the :variation,variation and instead treating the entire string as the font family. This is not happening with the google loader.

My code:

// load the fonts
WebFont.load({
  google: {
    families: [ 'Yanone Kaffeesatz:700', 'Droid Serif:bold,regular' ]
  },
  custom: {
    families: ['Computer Modern Serif:bold,regular'],
    urls: [config.staticRoot + "/assets/fonts/serif/cmun-serif.css"]
  },
  // when the fonts are loaded, have to refresh the scrollspy because the new font changed div positions
  active: function() {
    if (window.doc) {
      console.log("webfont active", window.doc);
      window.doc.$.contentBody.refreshSpyOffsets();
    } else {
      console.log("webfont active before app created");
    }
  },
  fontinactive: function(family, fvd) {
    console.log("error", family, fvd);
  },
  fontactive: function(family, fvd) {
    console.log("loaded", family, fvd);
  }
});

The console output:

> loaded Yanone Kaffeesatz n7
> loaded Droid Serif n7
> loaded Droid Serif n4 
> error Computer Modern Serif:bold,regular n4

I've been looking through the code but can't find where the parser is (isn't) being called. Help appreciated.

David

IE8 error when using typekit with webfontloader

I'm loading in typekit via the webfontloader api at i'm now getting a 'Invalid argument' on this line in the loaded typekit js file:

i.style.font="200px "+V+","+R

I don't remember seeing this before when testing previously, but it is now happening on a few sites.

if i load the file in directly: <script src="http://use.typekit.com/axh0err.js"></script> it doesn't error.

Webfont Loader injected classes show fonts are stuck on loading (ie. .wf-loading) but callbacks indicate fonts have loaded - fonts.com (Monotype)

Seems to be similar to Issue #17. I'm using v1.0.31 and have observed the issue in Safari, Chrome, Firefox. It occurs more frequently in Safari.

When loading fonts from Monotype (fonts.com), intermittently (sometimes up to 50% of the time), the Webfont Loader remains stuck on .wf-loading etc. whereas the font active events correctly show that the fonts have loaded. Check out this screenshot.

The problem manifests itself when trying to use the injected classes to do FOUT prevention.

I could simply use the font events to inject the equivalent (correct) classes, but I guess that's what the Webfont Loader is trying to do anyway!

I suspect that it is a timing/cache related issue because it seems to only occur when most of the resources are being loaded from cache - the problem never occurs when doing a cmd-refresh. It is also fairly intermittent, but sometimes occurs frequently.

A sample page demonstrating the problem (keep clicking on the links repeatedly - might require a bit of patience as the issue manifests itself fairly infrequently at times).

Note that I use exactly the same code and haven't observed these issues loading fonts from Typekit and Google Web Fonts.

Occationally fonts don't load. Cache related.

Noticed in Firefox 4 beta 4

The font wasn't loaded, and refreshing or going to a separate page didn't load the font. Shift-Refresh worked and the font is loaded on subsequent pages.

FEATURE REQUEST: Manually specify the name, path to font files, and formats, and WebFont picks the best font file to load...

So the Custom module is close to what I need, but not quite there. I'd like a module where the CSS sheet isn't external, but dynamically created and appended to the document via JavaScript. In the end, I'm hoping for an API similar to this:

WebFont.load({
  manual: {
    name: "Arial",
    path: "./fonts/Arial",
    formats: ['woff', 'ttf', 'eot']
  }
});

Where the files were available relative to the document root at:

./fonts/Arial.woff
./fonts/Arial.ttf
./fonts/Arial.eof

WebFontLoader would have to know which types the current User-Agent supports and picks the best one to load by dynamically creating a <style> node appropriately formatted.

Any thoughts? Thanks in advance!

webfont.FontApiUrlBuilder trying to load fonts locally when using local protocol

Tried to fork the project and add the conditional to make this work locally, but it's been trying to create the fork for hours. Basically, in fontapiurlbuilder.js the protocol is defaulting to whatever the document's protocol is, so when working with a local static file, you never access the font file. Instead, if you check the protocol to see if it's not http: or https: and prepend the url string, it works locally. Example replacement code:

webfont.FontApiUrlBuilder = function(apiUrl) {
  this.apiUrl_ = apiUrl || webfont.FontApiUrlBuilder.DEFAULT_API_URL;
  var protocol = window.location.protocol;
  if (protocol != "http:" && protocol != "https:") {
    this.apiUrl_ = "http:" + this.apiUrl_;
  }
  this.fontFamilies_ = null;
};

Active event and Webkit

As others have reported, the active event sometimes fires before the font is actually applied. This only happens in Webkit. I've read all the issues and comments and think I might have the beginning of a solution. After a bit of experimenting I found a way to detect the problem without browser detection.

The trick is to set a fixed font-size and family on the element that is used for monitoring the file size. Then when changing the font-family to trigger loading the external font, you specify the previous font-family as well. For some reason Webkit will then fall back to that font while loading the external one (instead of a unknown platform specific font.)

I've combined this with a small "ruler" font that provides a consistent baseline to detect font changes and created a small @font-face load detection library. The source is available in a Github repository: https://github.com/bramstein/fonzie

I've tested it on the devices I have access to, but it obiously needs more testing. If this turns out to be an improvement to the way the @font-face load detection is done, is there any interest in integrating this into the webfontloader?

Fonts.com leaving a blank style attribute

I'm using the following config. When I do this various elements on the page are left with a blank style attribute. [h2 style] Heading [/h2]. I've tried using other configs like Google and custom, these work properly.

WebFontConfig = {
monotype: {
projectId: 'my project id'
}
};

wf-active/wf-inactive classes activated way too late as of lately

Hi,

On a site of mine I'm using webfont.js (loaded from //ajax.googleapis.com/ajax/libs/webfont/1/webfont.js.

I'm also using

.wf-loading h1,
.wf-loading h2,
.wf-loading h3 {
    visibility: hidden; 
}
.wf-active h1 .wf-inactive h1,
.wf-active h2 .wf-inactive h2,
.wf-active h3, .wf-inactive h3 {
    visibility: visible;
}

To avoid FOUTs.

and in HTML:

    <script>
    window.WebFontConfig = {
      google: { families: ['Open+Sans:300,700,400', 'Allan:bold'] }
    };
    </script>
    <script src="//ajax.googleapis.com/ajax/libs/webfont/1/webfont.js"></script>

However as of this week the headings are hidden for many seconds (up to 3-10 seconds). This is happening in both Chrome (Mac) and IE8 (Windows XP) for me.

When debugging in Chrome I can see that both the fonts are loaded, and the document-ready as well as the window-onload event have been fired long before the headings are appearing.

When I switched back to 1.0.21/webfont.js everything was fine.

1.0.23 not available?

Somehow I can't get 1.0.23 to install. Bundler fails, and gem install webfontloader exits with

ERROR:  Could not find a valid gem 'webfontloader' (>= 0) in any repository
ERROR:  Possible alternatives: webfontloader

Also, downloading it from Rubygems fails (NoSuchKey); however the version page for 1.0.23 is present. 1.0.22 installs fine, by the way.

This isn't an issue with the gem's functionality, so this issue queue might not be the appropriate place to post this, but I'm quite perplexed and thought you should know about this. I'm wondering that nobody else noticed anything, the new version has been out for a while... does the above link work for you?

Google CDN version, "blocking" documentation, wait interval for fontinactive event, general syntax

Thanks for an awesome, indispensable script. Some questions:

  1. Why does the google CDN only have up to v1.3.0? Can they be pressured to push revisions sooner? :)

  2. How exactly does "blocking" work? It's in a couple demos. I would love to see this broken down in the readme in a bit of detail.

  3. How much time does the script wait until the fontinactive event fires, and the script basically just stops listening for it to arrive? It's pretty opaque as it stands. Would it make sense to make this developer-configurarable, possibly on a per-vendor basis? Please explain this interval in the readme, what server response (or non-response) is triggering it exactly, and expose an option, if at all possible.

  4. The google documentation is currently using an older syntax of:

WebFontConfig = {
        google: { families: [ 'Tangerine', 'Cantarell' ] }
 };

The newer syntax for the exact same thing seems to be:

WebFont.load({
      google: { families: [ 'Tangerine', 'Cantarell' ] }
});

Is this just Google's docs not keeping pace with the modernization of the script, or is there some meaningful difference that I should be gleaning here?

More generally, the readme goes from total beginner to total expert way too fast for me. I would love to see more mid-level explanation in general.

Thanks again for maintaining this so diligently.

Google Font loader reports loading of font as failed even if the fonts is loaded correctly

I'm having this strange issue. I'm loading fonts with google font loader.

    var data = {
        active: call_resize,
        fontactive: bum,
        fontinactive: bam,
        custom : {
            families : [ 'League Gothic', 'FontAwesome' ],
            urls : [
                    'http://localhost/wordpress/wp-content/themes-ai1ec/vortex/less/bootstrap/font-awesome.css',
                    'http://localhost/wordpress/wp-content/themes-ai1ec/vortex/less/bootstrap/font-league-gothic.css'
                    ]
        }
    };
    require(
        [ 'http://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js' ],
        function(  ) {
            WebFont.load(data);
        } );

Basically the two fonts are loaded correctly but the font loader report the second font as not being loaded correctly while this is not true as you can see from the image.

fonts

this is really tedious because i need to performa an action when all fonts are loaded and now Firefox and chrome are waiting for the failure before calling the "active" handler.

CSS before script tag breaks WebFont Loader

I ran into a problem with WebFont Loader, where it kept calling the ‘fontinactive’ callback, indicating that it could not load a font.
It turned out to be a CSS style rule that was included before the invocation of the <script> tag.
(We were invoking the WebFont Loader script dynamically via Javascript script injection, so it took a while to debug.)

I was able to reduce it to this test case (see below.) If you view it in Chrome it won’t show the desired fonts.
The same problem occurs when you change the asterisk '*' to 'span'.

<html>
  <head>
    <style type="text/css">
    * {
                font-family: arial, helvetica, tahoma, sans-serif !important;
                font-size: 14px !important;
    }
    </style>
    <script type="text/javascript">
      WebFontConfig = {
        google: { families: [ 'Tangerine', 'Cantarell' ] }
      };
      (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);
      })();
    </script>
    <style type="text/css">
      .wf-loading p {
        font-family: serif
      }
      .wf-inactive p {
        font-family: serif
      }
      .wf-active p {
        font-family: 'Tangerine', serif
      }
      .wf-loading h1 {
        font-family: serif;
        font-weight: 400;
        font-size: 16px
      }
      .wf-inactive h1 {
        font-family: serif;
        font-weight: 400;
        font-size: 16px
      }
      .wf-active h1 {
        font-family: 'Cantarell', serif;
        font-weight: 400;
        font-size: 16px
      }
    </style>
  </head>
  <body>
    <h1>This is using Cantarell</h1>
    <p>This is using Tangerine!</p>
  </body>
</html>

Long delay / blink loading monotype / fonts.com font

I'm seeing a long delay and blink, around 2 seconds, when loading a monotype config. This seems to be a recent happening as it worked a few weeks ago. See this very simple example. If I swap out monotype for a google font, the problem goes away. The blue square also blinks.

<!DOCTYPE html>
<html>
<head>
    <title>Content types | ET United States</title>
    <script src="http://ajax.googleapis.com/ajax/libs/webfont/1.1.2/webfont.js"></script>
    <script type="text/javascript">
    WebFont.load({
        monotype: { projectId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' }
    });
    </script>
</head>

<body class="html not-front logged-in no-sidebars page-admin page-admin-structure page-admin-structure-types domain-exacttarget-us site-name-hidden">
    <h1 style="font-family:'Helvetica W01 Roman'">WTF Blink</h1>
    <div style="width:100px;height:100px;background-color:blue;"></div>
</body>

</html>

Race Condition with Google Chrome 19.0.1084.52 m on Windows 7

It seems active() is called when the font is not yet ready.

Project site: http//meshcraft.net or http//meshcraft.net/devel.html for a non-compressed version
It is a sole Canvas where everything is drawn in, so its supposed on load to wait for the webfonts to been loaded. WebFont.active() is now calling startup() what used to window.onload directly before.

Every once in a while (1 in 10-20 cases for me) when Ctrl-Refreshing, Chrome will not draw anything, since the font seems to be not really ready yet. Maybe my imagination, but I believe the more tabs I've open the more likely the race condition applies.

Thats the code that handles startup now:

(function(){
'use strict';
if (typeof(window) === 'undefined') { throw new Error('this code needs a browser!'); }

window.onload = function(){
WebFont.load({
        custom: {
                families: [ 'DejaVuSans', 'DejaVuSansBold' ],
                urls: [ '/fonts/dejavu.css' ]
        },

        active: function() {
                console.log('active');
                startup();
        },

        fontactive: function(ff, fd) {
                console.log('fontactive ' + ff + ' ' + fd);
        }
});
}

})();

Fontwatcher spans: excessive width at small screen sizes

The Fontwatcher spans are making the width of a given site too wide at the mobile size until they disappear after 40 secs.

Not sure if it has any relevance, but I am using the Zurb foundation framework which makes extensive use of the box-sizing: border-box; declaration.

Anyone know of a fix / workaround?

(using WFL 1.3.0)

fontactive signal in browser race condition

I'm trying to use $(element).width() on an element that uses a WebFont-loaded font.

With jQuery, I:

  1. Use WebFont's "fontactive" signal like this: fontactive: $(function() { $('html').trigger('wf-fontactive', ...) });
  2. $('html').bind('wf-fontactive') and, in the handler, read $(element).width()

However, in Firefox and Webkit, there's a race. The wf-fontactive signal is fired (and the $('html') class is added) after the font is loaded, but the browser doesn't render it right away. The browser does its width calculations with Helvetica or Arial instead.

I've put up an reduction here: http://adamhooper.com/webfont-test.html -- unfortunately, this bug seems to stem from a race condition so it's more frequent on complex sites than on this simple one. But refresh the page a hundred times in Google Chrome (tested on 15.0.865.0 dev) and you should see the first "width" change after a few quick refreshes.

Here's what I see, maybe 5% of the time:

This is text in another font.

Log:

Triggering wf-fontactive...
In wf-fontactive
width: 408
Waiting until later...
Okay, it's later
width: 259

I believe Firefox has the same issue, though I can't reproduce it with this reduction.

Similar to #32

Add support for custom test strings

I had a look at this today, and I think we have several options for going about this:

  1. Exposing a single configuration parameter, so all fonts loaded for a single call will use the same configurable test string:
webfont.load({
  typekit: {
    id: '...'
  },
  testString: 'abcdefg'
});

If you need to load two fonts with different test strings you'll need to make two calls to load.

  1. Test strings per font. Using a single load call with multiple test strings:
webfont.load({
  google: {
    families: ['Droid Sans', 'Droid Serif'],
    testStrings: ['abcdefg', 'hijklmo']
  }
});

Or some variant thereof. This might be a bit of a problem for modules that use identifiers instead of font families, but perhaps being able to specify test strings through the module interface is good enough for them (the interface for that is already there.)

Uncaught TypeError: Property 'i' of object [object DOMWindow] is not a function

in chromium 6.x i get this error only occassionally:
Uncaught TypeError: Property 'i' of object [object DOMWindow] is not a function
ajax.googleapis.com/ajax/libs/webfont/1/webfont.js:26

Dragging out the minified source, this seems to be the only i spot on line 26:
i(a.c, "html", c);

Which appears to be this line.. L121 of fontwatcher.js
this.domHelper_.insertInto('html', span);

Maybe it's a race condition but the scope resolution to identify i fails sometimes.

Allow disabling font support at runtime

I propose the following API, which is passed an instance of WFL's UserAgent object and returns a boolean.

WebFont.load({
  enabled: function(userAgent) {
    // No fonts in IE
    return userAgent.getName() != 'MSIE';
  }
});

Thoughts?

Using Webfont.load more than once: Active event fired before font is loaded

Hi and thanks for this great library.
I am working on a small site that show off the webfont capabilities:

Users can choose among multiple fonts form a dropdown menu but I have a problem using webfont load more than once.

If I call WebFont.load({ google: {families: [ fontFamilyURL] }, more than once in the same page, its events work as expected only for the first time.

The second time the font is loaded but the loading events are not fired in the expected order: the loaded and active events are fired before the font resource is actually available!

This means I cannot process the new font correctly (ie. check the width of a word) because the app thinks that the font is loaded before it actually is!
I tried a solution where I am running a loop that updates the font but it is not ideal.

Is there a solution to this? Can Webfont loader be somehow reset to be used more than once?

Thanks
Riccardo

Active Event not firing in IE8 (using fonts.com)/ IE9 fires twice

Thank you in advance for reading.

I am using fonts from a fonts.com/webfonts account but the active event is not firing in IE8.
Works fine in IE7, IE9, Firefox, Chrome etc - just IE8!

Update - just noticed that all the script called after the active event happens twice in IE9.

Anyone else had this problem?

Many Thanks,
Carine

FontWatcher erroneously reports successful load on iOS 6

In iOS 6 I seem to be getting early reports of fonts being loaded using the custom loader. The first check always reports the font is loaded, which was not happening a while ago. I think this is related to the use of height when comparing nodes. Previously, only width was used. I played a bit with creating FontRulers on iOS and have observed that a style that references just serif or a bogus font (no associated @font-face rule) and serif will return one height, but a real font and serif reports a different height. However, that other font is clearly not loaded (serif and sans-serif fallbacks for it report different widths). I created 3 rulers, one for 'serif', one for 'MyFont, serif' and one for 'ABCxyz, serif'. There was an @font-face rule for MyFont, but not ABCxyz. The returned sizes are:

serif: 1894 x 553
MyFont, serif: 1894 x 645
ABCxyz, serif: 1894 x 553

I have no idea why MyFont has a height of 645. This happens even if the src in the @font-face is bogus (the font can never load). Something about having the rule changes the height. I locally stopped checking height in Size.equals() and then the fonts correctly loaded. I have only observed this in iOS (and only test in 6.0). It may be reasonable to stop checking height, but I don't know why that check was added in the first place. Consistency? In any case, it seems like height is easily manipulated with line-height styling (say, .25in on body) so perhaps it is not a terribly useful check.

support for waiting for fonts to load in iframes

I'd like to create an empty iframe and wait for webfonts to finish loading in it before filling it with content. I can currently do that by referencing webfontloader in the iframe and using cross-frame communication, but my use case would be simpler if I could load webfontloader in the parent and tell it which frame to load the fonts in.

I propose changing the API to add an optional context argument to WebFont.load (a la jquery).

To get an idea for the scope of the change, here's a branch where I've added this feature: https://github.com/ryanwolf/webfontloader/compare/iframes

Active firing too early on WebKit browsers

On WebKit browsers (Chrome and Safari) under Windows when using custom module Webfont loader fires fontactive and active (the same holds for the wf-active class) before fonts become displayed and the page is laid out using loaded font metrics.

I tried everything but the flicker is still here

Hello everyone

Yes yes yes I know ... there are solutions to avoid the famous flicker and FOUT but in my case it's still here.

I already tried everything, for example applying "visibility: hidden;" to all these elements and then "visibility: visible;" when the CSS class ".wf-active" is set in the top HTML element.

I'm very very happy to point you to the example page but my client wants to keep it password protected for now. So I'd be very grateful if you could contact me by email for access.

It's very difficult to solve the flicker and I already tried some extreme solutions. Noone of these were working. Each time I use a cold reset / reload within Firefox I see the default font then the custom font. One flicker.

Thank you very much for your time and attention!

Greetings from New Zealand
M.H.

Webfontloader stuck on 'wf-loading' even after all fonts are loaded

Hi there,

For some unknown reason, the webfont loader is able to load up the fonts on my site (so you have the class 'wf-my_font-n4-active) but the webfont loader still remains in the loading phase and does not switch to active (and this behavior only started occurring today without any code changes on my end). Is there a specific behavior that would cause the webfontloader api to not pick up that all the fonts have been loaded (you can see this in effect at http://experience.calarts.edu/ whereby the fonts are active but the over webfont loader is still stuck in loading).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.