Open In App

Web API CSS Font Loading

Web API CSS Font Loading is used to add CSS styles on web pages. It handles the dynamic change which occurs on the web page. We can create a @font-face rule and can add any kind of CSS that we want to load on a page. It also helps in not delaying the styling on the web page. It has many features like FontFace.status which can set the status for loading of FontFace.

Web API CSS Font Loading Interfaces

Web API CSS Font Loading Properties

Web API CSS Font Loading Events

Example: In this example, we are loading a font and applying all the events of FontFaceSet.




const result = document.getElementById("result");
 
const canvas = document.getElementById("js-canvas");
canvas.width = 650;
canvas.height = 75;
const ctx = canvas.getContext("2d");
 
const oxygenFontFace = new FontFace(
    "FontFamily Kdam Thmor Pro",
    "url(
);
document.fonts.add(oxygenFontFace);
result.textContent +=
    `font status: ${oxygenFontFace.status}\n`;
 
document.fonts.load("36px FontFamily Oxygen").then(
    (fonts) => {
        result.textContent +=
            `Bitter font: ${fonts}\n`;
        result.textContent +=
            `Bitter font: ${oxygenFontFace.status}\n`;
        ctx.font = '36px "FontFamily Oxygen"';
        ctx.fillText(" Kdam Thmor Pro font loaded", 20, 50);
    },
    (err) => {
        console.error(err);
    },
);
 
document.fonts.addEventListener("loading", (event) => {
    result.textContent +=
        `loading_event: ${event.fontfaces.length}\n`;
});
document.fonts.addEventListener("loadingerror", (event) => {
    result.textContent +=
        `loadingerror_event: ${event.fontfaces.length}\n`;
});
document.fonts.addEventListener("loadingdone", (event) => {
    result.textContent +=
        `loadingdone_event: ${event.fontfaces.length}\n`;
    event.fontfaces.forEach((value) => {
        result.textContent +=
            `  fontface: ${value.family}\n`;
    });
});
 
document.fonts.ready.then(function () {
    result.textContent +=
        `\nFontFaces in document: ${document.fonts.size}.\n`;
 
    for (const fontFace of document.fonts.values()) {
        result.textContent += "FontFace:\n";
        for (const property in fontFace) {
            result.textContent +=
                `  ${property}: ${fontFace[property]}\n`;
        }
    }
});




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
 
<body>
    <canvas id="js-canvas"></canvas>
    <textarea id="result" rows="30"
              cols="50">
      </textarea>
</body>
 
</html>

Output:

Output

Browser compatibility:


Article Tags :