How to Load Google Fonts with JavaScript

resources
Published on November 19, 2019

Use-Cases of this tutorial

  • Know how to load Google Fonts in Javascript instead of including through a CSS stylesheet
  • Know about the Web Font Loader library that can be used to load fonts in web pages.

Google Fonts can be loaded through Javascript using the Web Font Loader Library.

The usual way of including Google Fonts in webpages is through a <link> element, similar to how CSS files are included :

<link href='https://fonts.googleapis.com/css?family=Roboto:300,400,700' rel='stylesheet' type='text/css'>

However Google Fonts can be loaded using JavaScript also. This is done using the Web Font Loader Javascript library.

Using Web Font Loader Library to Load Google Fonts

  • Include the Web Font Loader's script file.

    <script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>

    The latest version can be found from Google Hosted Libraries.

  • Then include Javascript to load the required Google Fonts.

    <script>
    	WebFont.load({
    		google: {
    			families: ['Roboto:300,400,700']
    		}
    	});
    </script>
    

    Multiple fonts can also be loaded.

    WebFont.load({
    	google: {
    		families: ['Tangerine:300i,400i,700,700i', 'Open Sans:300']
    	}
    });
    

    There are also events to know when fonts are being loaded, or have been loaded.

    WebFont.load({
    	google: {
    		families: ['Roboto:300,400,700']
    	},
    	loading: function() {
    		console.log("Fonts are being loaded");
    	},
    	active: function() {
    		console.log("Fonts have been rendered")
    	}
    });
    

Loading Web Font Loader Asynchronously

To boost performance, Web Font Loader can be loaded asynchronously also.

<script>
	WebFontConfig = {
		google: {
			families: ['Roboto:300,400,700']
		}
	};

	(function(d) {
		var wf = d.createElement('script'), s = d.scripts[0];
		wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js';
		wf.async = true;
		s.parentNode.insertBefore(wf, s);
   	})(document);
</script>

Note that you need to define the global variable WebFontConfig explicitly in this case.

Other Features about Web Font Loader

Web Font Loader Library has other features also, like :

  • Setting a timeout to load fonts
  • If multiple fonts are being loaded, events are triggered for each font
  • Events to know whether the font is not supported by the the browser, or if the font cannot be loaded.
  • Loading fonts from Typekit, Fonts.com & Fontdeck

Visit Web Font Loader Github's page for the complete documentation.

In this Tutorial