Skip to content

Dumbed Down version of “Optional Polyfill" #3

Open
@MarcoHengstenberg

Description

@MarcoHengstenberg

Regarding the technique of using the native Fonts API while making sure we provide a fallback for non-supporting browsers, I came to the conclusion that I didn't even want to include a polyfill (like FontFaceObserver) for IE and/or Edge.

The final script looks like this:

(function() {
    "use strict";
    // Optimization for Repeat Views
    if( sessionStorage.fontsLoaded ) {
        document.documentElement.className += " fonts-stage-1 fonts-stage-2 ";
        return;
    // Check if the Fonts API is supported,
    } else if( "fonts" in document ) {
        // then load our critical Font first,
        document.fonts.load("700 1em AmmanSans") && document.fonts.load("700 1em SourceSansPro").then(function () {
            document.documentElement.className += " fonts-stage-1 ";
            // then load the other fonts.
            Promise.all([
                document.fonts.load("400 1em AmmanSans"),
                document.fonts.load("400 1em SourceSansPro")
            ]).then(function () {
                document.documentElement.className += " fonts-stage-2 ";
                // Write to sessionStorage for repeat views.
                sessionStorage.fontsLoaded = true;
            });
        });
    } else {
        // Use polyfill/fallback for non-supporting browsers.
        sessionStorage.fontsLoaded = true;
        document.documentElement.className += " fonts-stage-1 fonts-stage-2 ";
    }
})();

What I'm doing is:

  • look for fontsLoaded to be true in the sessionStorage and stop if that's the case, while writing my classes on the <html> element.
  • if not: I take the Fonts API and load the Webfonts asynchronously in supporting browsers, while setting fontsLoaded to true in the sessionStorage after I made sure the fonts have indeed loaded.
  • else: if the Fonts API is not supported (IE and Edge), we simply set the fontsLoaded to true in the sessionStorage and add those classes.

Any repeat view, whether with Fonts API or not will be safe, all modern browsers will be safe and IE + Edge get a pretty basic but working solution for loading fonts.

The advantage for us is: we do not need to work with a polyfill at all, while being sure that Webfonts are loaded in all browsers. IE and Edge will load them via font-face and the rest via Fonts API.

I suppose this is way too easy to be a viable solution but one can hope. What do you think Zach?

Errr… yeah. 😃

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions