Home > Mobile >  Add CSS if font does not load
Add CSS if font does not load

Time:02-10

With document.fonts.ready.then, it is possible to change CSS if a font is loaded.

Example:

document.fonts.ready.then(function() {
  $("div").css("color", "blue");
});
@font-face {
  src: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/133207/moderna_-webfont.ttf") format("truetype");
  font-family: "font";
}

div {
  font-family: "font";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>Lorem ipusm</div>

Now my question is: Does something like document.fonts.NOT.ready.then exist? Or how can I change the CSS if the font gets not loaded?

Would be very thankful for help.

CodePudding user response:

MDN suggests you can check for

document.fonts.status == 'loading'

or .check() for specific font(s).

For errors add an event handler for onloadingerror

In the test snippet below, .status changes to loaded immediately, there's a Failed to load resource immediately, but neither .ready nor .onloadingerror are called at that time, instead wait for 2 minutes then you get both .ready and .onloadingerror events fire along with another GET ERR_CONNECTION_TIMED_OUT error (ensure browser console is open)

This is likely just due to the url for the font - a closer match to a valid font may return quicker or a 403 may return quicker etc

document.fonts.ready.then(function() {
  $("div").css("color", "blue");
  $("div").text(document.fonts.status);
});

document.fonts.onloadingerror = () => {
  $("div").css("background-color", "pink");
}

$("div").text(document.fonts.status);
@font-face {
  src: url("https://badurl.com/moderna_-webfont.ttf") format("truetype");
  font-family: "font";
}

div {
  font-family: "font";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>Lorem ipusm</div>

  • Related