GoogleChrome / webdev-infra

Apache License 2.0
37 stars 28 forks source link

Reuse icons via `<svg use>` #44

Open matthiasrohmer opened 1 year ago

matthiasrohmer commented 1 year ago

The way we embed SVGs on the sites is not ideal. They are usually inlined, causing duplicate code to be shipped across the network. For example:

https://developer.chrome.com/en/docs/devtools/javascript/reference/ - which uses the Gotcha aside seven times, we inline the same 372 byte SVG seven times, which sums up to 2,54KB of which 2,17KB could be saved.

Not much, but there are other shortcodes which use more heavy icons, like the BrowserCompat shortcode made available for both sites with https://github.com/GoogleChrome/webdev-infra/pull/41. This is used 17x on https://web.dev/learn/css/pseudo-classes/#hover, adding 18,4KB of SVG code to the site for each instance, totalling in 312,8KB.

Other pages on web.dev that use BrowserCompat more than 2x:

By introducing a helper that keeps track of the used icons per page, we could avoid shipping duplicate bytes and also improve DOM size. This would work by giving each SVG an ID and then reuse it like this:

<svg viewBox="0 0 22 22">
  <use href="#firefox-logo" />
</svg>
matthiasrohmer commented 1 year ago

For now https://github.com/GoogleChrome/webdev-infra/pull/41#issuecomment-1384285465 works around this using CSS background images with data URLs to avoid HTTP requests. Not great for maintenance, but performant at least.