Wait for fonts to load before rendering web page

后端 未结 11 1370
终归单人心
终归单人心 2020-11-27 15:38

I\'m using @font-face to embed fonts in my website. First the text renders as the system default, and then (once the font file has loaded presumably) the correct font render

11条回答
  •  伪装坚强ぢ
    2020-11-27 16:22

    I had a similar problem while rendering to an HTML canvas, and this was my solution. It's based on the FontFace API, and similar to Holtwicks approach. The key differences are that this is a generic approach and that it will work out-of-the-box for external fonts/stylesheets (e.g. google fonts).

    A couple of notes; fonts.load( ... ) will happily resolve with an empty set of fonts if the font isn't known yet. Presumably, this happens if this code is called before the stylesheet declaring the font was added. I added a fonts.check(...) to overcome that.

    This will let you await javascript execution until a font is available, so it won't work out of the box for 'normal' HTML content. You can combine this with Holtwicks answer above.

    export async function waitForFontLoad(
        font: string,
        timeout = 1000,
        interval = 10
    ) {
        return new Promise((resolve, reject) => {
            // repeatedly poll check
            const poller = setInterval(async () => {
                try {
                    await document.fonts.load(font);
                } catch (err) {
                    reject(err);
                }
                if (document.fonts.check(font)) {
                    clearInterval(poller);
                    resolve(true);
                }
            }, interval);
            setTimeout(() => clearInterval(poller), timeout);
        });
    }
    

提交回复
热议问题