Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if Font Awesome is loaded in web page with javascript?

I need to check if a web page has Font Awesome in it. If not I'm going to load it with javascript. Kinda like how the facebook sdk checks to see if there is a script element containing the id "facebook-jssdk", if so it just returns (does nothing), if not it loads it. I need to do that for Font Awesome.

like image 800
cmac Avatar asked Aug 01 '16 14:08

cmac


People also ask

How do I know if Font Awesome is loaded?

With Font Awesome there's no JavaScript to detect. One way we can detect Font Awesome is by creating an element and checking if the correct CSS is applied to it.

Can you use Font Awesome in JavaScript?

Font Awesome works well with Require. js, especially if you are using Web Fonts.

Why is my Font Awesome not showing?

If you installed the Free Font Awesome version but try adding Pro icons to your web pages, they won't show. The solution to this is either you use the alternative free icons or upgrade to a Pro subscription/license.


1 Answers

I think this is the best way to check for font-awesome, but I'm not sure if it's slower then just loading it again even if it is there.

function css(element, property) {
  return window.getComputedStyle(element, null).getPropertyValue(property);
}

window.onload = function () {
  var span = document.createElement('span');

  span.className = 'fa';
  span.style.display = 'none';
  document.body.insertBefore(span, document.body.firstChild);

  if ((css(span, 'font-family')) !== 'FontAwesome') {
    // add a local fallback
  }
  document.body.removeChild(span);
};
like image 102
cmac Avatar answered Oct 03 '22 21:10

cmac