avris/fontawesome-optimiser

Optimise FontAwesome using SVG sprites

v0.2.1 2020-05-05 21:59 UTC

This package is auto-updated.

Last update: 2024-03-06 06:33:31 UTC


README

Optimise FontAwesome using SVG sprites.

FontAwesome provides thousands of icons, but you probably only use a few dozen on your website. Instead of loading all of them as a webfont, you could use SVG sprites.

This library is a simple helper that:

  • registers the icons you use in the place you use it,
  • dumps a refined set of SVG symbols at the end of your page.

You can check out a blog post about possible gains.

Pitfalls

Warning: it's just an early version and it's not suited for every website!

It might not work well, if:

  • you load content containing icons dynamically,
  • you use caching in a way that won't trigger the Optimiser,
  • you want the icons to be cached in the browser between pages,
  • if you're using a looooot of icons,
  • ...

Installation

composer require avris/fontawesome-optimiser

Instantiate the Optimiser, pointing it to the FontAwesome SVG files and optionally selecting a default icon set:

$fonts = new \Avris\FontawesomeOptimiser\Optimiser(
    __DIR__ . '/node_modules/@fortawesome/fontawesome-pro/sprites',
    'light'
);

If you're using Twig, register an extension:

$twig->addExtension(new \Avris\FontawesomeOptimiser\TwigExtension($optimiser));

If you're using Symfony, here's how to register a Optimiser as a service:

services:
    Avris\FontawesomeOptimiser\Optimiser:
        arguments:
            $spritesDir: '%kernel.project_dir%/node_modules/@fortawesome/fontawesome-pro/sprites'
            $defaultSet: 'light'

    Avris\FontawesomeOptimiser\TwigExtension: ~
    

Also, include this CSS so that the SVGs are displayed like webfonts:

.icon {
    width: 1.1em;
    height: 1.1em;
    vertical-align: -.125em;
    fill: currentColor;
}

Usage

Wherever you want to display an icon, use:

$icons->icon('user');           // far fa-user
$icons->icon('brands gitlab');  // fab fa-gitlab
$icons->icon('fab gitlab');
$icons->icon('gitlab', 'brands');

This will save this icon as used and render tags with a reference to a symbol, like:

<svg class="icon"><use xlink:href="#regular-user"></use></svg>

Before the closing </body> tag, use:

$icons->iconSprites();

Which will render the actual definitions of the used fonts:

<svg xmlns="http://www.w3.org/2000/svg" style="display: none;"><symbol id="regular-user">...

In Twig you can use functions:

{{ icon('user') }}

...

{{ iconSprites()}} 

Copyright