sciencehistory / scihist_digicoll

Science History Institute Digital Collections
Other
11 stars 0 forks source link

Improve inline svg use, to avoid duplicate svg bytes #2482

Closed jrochkind closed 2 weeks ago

jrochkind commented 7 months ago

We like inline svg's because they are styleable with CSS, which we use mainly for color.

We output direct inline svg in a simple naive way from eg https://github.com/sciencehistory/scihist_digicoll/blob/master/app/helpers/bootstrap_file_icon_svg_helper.rb

In some cases it's nice to use inline SVG to avoid an extra http fetch -- but if we have a bunch of the same svg on a page, this inlines it many times duplicated! It might be better to have an external SVG file we reference, that can be fetched once and cached by the browser.

Is there a way to do this, but still keep svg css styleable? Turns out yes... using the SVG symbol and use features...

Usually these are demo'd with an inline svg on the page with one or more symbols... but that is hard to deal with in our Rails view architecture.... different components at different parts of the page may want to insert an SVG, how we trigger the "symbol" svg to be included once and only once, but only for images used? (we don't really want to inline every svg we might possibly use!)

It turns out, though, it looks like you can also have an svg you reference at an external URL and add on a #symbol-id on the end to reference a specific symbol inside that svg... and it works?

It looks like there are some weird tricks though... the referencing svg might need to duplicate the viewBox attribute to have it sized right, that isn't re-used properly from the symbol for whatever reason. might be something like:

# "<svg viewBox='0 0 384 512'><use xlink:href='#{asset_path("svg_symbols/some-file.svg#some-id")}'></svg>".html_safe

Where that file in asset path might just look like:

# in app/assets/svg_symbols/some-file.svg
<svg xmlns="http://www.w3.org/2000/svg" style="display:none">
  <symbol id="some-id" fill="currentColor" viewBox="0 0 384 512">
    <path  ....   />
  </symbol>
</svg>

I haven't seen much discussion of this on the web though... this seems so convenient, why not? Is there something I'm missing?

We could look into this and optimize our inline SVG use if it works out.

OR it might not matter cause it's not very many bytes.

jrochkind commented 7 months ago

Some resources, although I haven't found one that specifically spells out this pattern! But ones that had pieces I put together.

https://github.com/jamesmartin/inline_svg/issues/124

https://github.blog/2016-02-22-delivering-octicons-with-svg/#our-approach

https://github.com/jgarber623/svgeez

jrochkind commented 2 weeks ago

You know what, this doesn't matter much, svg's are pretty small and we don't duplicate them much.