typekit / webfontloader

Web Font Loader gives you added control when using linked fonts via @font-face.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bug: Duplicate HTML tags for already loaded fonts.

SimonHoiberg opened this issue · comments

I would consider this a bug, otherwise, please consider this a feature request 🙂

Scenario
Say I make a call to request a specific font at 3 different times during runtime.

WebFont.load({
 google: {
   families: ['Montserrat']
 }
});

Desired behavior
After the first load, the two subsequent calls to WebFont.load gets ignored.

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat" media="all">

Actual behavior
3 identical HTML tags and 2 reduntant requests.

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat" media="all">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat" media="all">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat" media="all">

If you work with webfontloader in a context where fonts are loaded conditionally during runtime, it becomes rather inconvenient to make all the checking before requesting a font.
I hope this will be fixed sometimes soon 😊

I don't think a "fix" would be necessary as proposed above, but a config option would be awesome. It should provide the ability to optionally include the urls object if the link to the stylesheet is not already included in the DOM. As it stands anybody facing this seems to have to engage in some form of hacked solution to avoid this...

Anyone with a workaround for this?

I guess you could do something like this:

const link = document.querySelector('link');
const fontUri =  'https://fonts.googleapis.com/css?family=Montserrat';
if (!link || !link.hasAttribute('href') || link.getAttribute('href') !== fontUri ) {
  WebFont.load({
     google: {
       families: ['Montserrat']
     }
   });
}

If there are other links in the head

const fontURI = 'https://fonts.googleapis.com/css?family=Montserrat';

function checkForLinks() {
  const links = Array.from(document.head.getElementsByTagName('link'));
  if (!links || !links.length) return false;

  return links.find(
    link => link.hasAttribute('href') && link.getAttribute('href') === fontURI
  );
}

const fontLink = checkForLinks();

if (!fontLink) {
  WebFont.load({
    google: {
      families: ['Montserrat'],
    },
  });
}