Isn't the fundamental issue here not so much anything to do with `<svg>`, but with the fact that you can't easily include HTML snippets from other files in HTML? Like, the only reason not use the <svg> tag seems to be "it's not cached, and it contains a BUNCH of svg, and it has to be loaded with the main HTML page"
Can't you say that about anything in HTML? Like, imagine you had a huge `<head>` tag that contained a bunch of stuff, but it's essentially the same (except for, like, the title) for all documents. Don't you wanna do this?
<html>
<head>
<<< include head.html >>>
<title>Cool page!</title>
</head>
<body>
<svg>
<<< include logo.svg >>>
</svg>
</body>
<html>
Where the `<<< include ... >>>` is a pretend bit of HTML that makes the browser fetch that from somewhere else. A preprocessor, more or less.
I realize this is what templating languages are for, but if this happened on the HTML layer, the browser could do way better caching.
One of the things said in there is that they look for usage of userland solutions. I mentioned in another comment, but there are custom elements that do client-side includes, like: https://www.npmjs.com/package/html-include-element
To me at least this feels like a fairly natural addition to HTML. You can already pull in external scripts, stylesheets, images, video, etc, so why not page partials too? A sibling comment mentions XSLT which is cool, but nobody knows about it because it doesn’t follow any patterns set in HTML and HTML doesn’t have any breadcrumbs that might lead someone to discover XSLT. Something like <partial src=“header.html”> flows with expectations much better.
Something I find a bit funny now is that for the longest time back in the 2000s, nearly the entirety of my usage of PHP was comprised of PHP includes to make up for this gap in HTML functionality (I had no idea XSLT existed then).
It had breadcrumbs back in 2004 (e.g. those neat "valid XHTML 1.1" badges from W3C back when badges on your website were cool, and e.g. W3 Schools actually put it above javascript[0]. XHTML was supposed to be the next big thing). These days it seems that browser vendors just don't like it for whatever reason (tinfoil hat on: because almost all of them benefit from javascript-based spyware, and so prefer a world where even static pages require javascript to be enabled to show anything), and so documentation acts like it is some legacy thing instead of what it is: a perfect fit for the 99% of websites that need some templates and don't have much dynamic interaction.
Other cool web tech that should have "won": XForms[1]. Imagine if HTML forms had things like declarative data-binding (with XPath expressions! Imagine jq built directly into the browser 20 years ago and usable by forms) and types/constraints/validation built right in. This would be 1000x more useful for your average web dev than something like USB or GPU support or Wasm. You'd be able to make complex interactive forms in much the same way that you do a spreadsheet.
One reason that this is slightly more complicated than it appears is that you have to decide what ignore when doing the inclusion. Including an image will not override anything specified in the "parent" HTML, but including HTML might result in conflicts. Who wins, who loses, etc. etc.
HTML does have a preprocessor. It's called XSLT, and it has includes, though they have no deferred fetch. Also, being a preprocessor, you can't interact with it after page load (unless you use a javascript implementation). It's been built into browsers for 20+ years. Still works great, but browsers never supported versions past 1.0 so it shows its age some.
Also, at least back when we excised the last bits of it from our old codebase, no useful caching of either stylesheets or included resources (other stylesheets), so if you tried to mix client-side processing with HTTPS you were in for quite some pain unless you had a fast, very low latency, uncongested, link.
Currently it looks like at least Firefox and Chromium both cache stylesheets and included files as you'd expect. In fact, you can use this to increase cacheability in general. e.g. when this site is having performance issues, it often works logged out/when serving static versions of pages. It's easy to make every page static by including a `/myuser.xml` document in the xsl template and using that to get the current logged in user/preferences to put on the page. This can then be private cached and the pages themselves can be public cached. You can likewise include an `/item-details.xml?id=xxxx` that could provide data for the page to add the logged in user's comment scores, votes, etc. If the included document fails to fetch, it falls back to being empty, and you get the static page (you could detect this and show a message).
XSLT 3.0 can be directed to output HTML5 [0]. However, browsers only implement XSLT 1.0, and as far as I am aware there is no open-source XSLT 3.0 implementation.
Still, it's possible with XSLT 1.0 to produce documents in the common subset of XML and HTML5 ("XHTML5"). It can't produce the usual <!DOCTYPE html> at the top of the document, but it can produce the alternative <!DOCTYPE html SYSTEM "about:legacy-compat">.
On the input side, every XSLT version only accepts valid XML, as far as I am aware.
`xsltproc --html` is an example of HTML input (probably HTML4 parsing rules though?) if you really need it. This is an XSLT 1.0 processor, wrapping libxslt which most browsers use.
As for output, the difference is largely irrelevant for browser purposes since they just want a tree.
I'm not sure how many extensions the browsers allow, but a major part of the reason XSLT 2/3 failed to take off is because libxslt already provides most of the useful features from newer versions as extensions (many via EXSLT-namespaced modules, at least partially supported in browsers - see MDN); what it doesn't do is implement the unnecessary complexity that the Java world loves.
At the time HTML was converted from SGML to XML:
https://en.wikipedia.org/wiki/XHTML
so if you authored XHTML, you could XSLT it. There is also XHTML5, an XML serialization of HTML5. I imagine in the real world there is a great deal of web that is HTML, accepted by browser, but not XML.
As far as I know, HTML5 has diverged from its origins enough that it's neither SGML nor XML. However, given the existence of XHTML5, it might be possible to parse an HTML5 DOM and re-serialize it as XHTML5, and thus it might be possible to take parseable HTML as input to XSLT, albeit with some indirection.
We were going to move on to XHTML after HTML4, for those variants (did it go beyond XHTML1.1?) HTML is XML compliant. That got caught in slow design-by-committee hell though so HTML5 became the defacto standard instead. There is XHTML5 which is an attempt to direct that back towards compliance, but I've never seen it used in the wild.
As I understand XSLT, it takes an XML document as input and an XML document describing the transformation, and produces an XML document as output.
But most HTML in the wild today is not valid XML. There is XHTML as mentioned by a sibling comment but it's rarely used. So if you were to start with an existing base of HTML documents, you couldn't easily add XSLT preprocessing to them. The issue is with the input rather than the output.
If you're using it as a template language for your own pages, you can of course just write it correctly (this is not different than needing to use correct syntax for react code to compile).
If you have someone else's documents, or need to mass convert your own to fix them, there's HTML tidy[0]. This one is quite useful to be able to run XML processing CLI tools on scraped web pages.
But the real power is in delivering XML to the client, not HTML. This lets you work in the domain model directly on the frontend, and use XSLT to transform that into HTML for display. So of course you'd use well-formed XML in that case.
Imagine if you didn't have a distinction between APIs and pages; you just returned the data along with a link to a template that says how to display it and (ideally) a link to a schema definition. Modifying templates for components could be as easy as modifying CSS attributes in the browser console, giving the next generation an easy way to peak and play around with how it all works as they're growing up. We were so close, and then things veered off into the hellworld that is the modern web.
HTML was invented as an SGML vocabulary, and SGML does have those inclusion mechanisms (called entities), though browsers basically never implemented those. To this date, self-acclaimed web folks ridicule XML (a simplified subset of SGML originalky invented as the base for additional vocabularies on the web, of which SVG and MathMl made it) for daring to incorporate something as basic as text variables/entities ie the "billion laughs atrack" (SGML could already limit the recursive entity expansion depth).
If we're talking just SVG, it could be done as a one-time inlining that uses <defs> to define shapes, that get pulled into the page later with <use>. The defs are page-wide and work across <svg> elements. That would fix the duplication, though not necessarily caching on its own with GP's include.
I think whether or not this makes sense on the client-side is up for debate.
Alternatively, though, SVGs in ``<svg>`` elements could just, yknow, retain their stylability. (is there a reason they don't? this has been a long-running frustration of mine)
Turbo Frames (https://turbo.hotwired.dev/handbook/frames) does this. It does mean pulling in a JavaScript library (and the user having JS enabled) but you don't have to write any.
I'd definitely love to see something like this built into the browser.
Yes, I want this and it would solve quite a few issues - particularly lazy loading and SPA-style content swapping could be done with better performance, because html can be easily processed and rendered during download by the browser (unlike the classic AJAX -> Json.parse -> render pipeline, which requires each step to be completed before the next one starts). Lazy loading would also not require JavaScript.
I may be completely off and/or misremembering, but isn't this what <object> was meant to be able to do/support? Seems that this could be done by convincing Apple/Google/Firefox to reframe/update how the object element works in modern browsers.
I like to use sprite files for conditional styling of icons, because using separate file for each state creates a visible delay on state changes, which doesn't look great.
You can make them with <defs> and <use> tags pretty easily if you understand svg a bit. I usually bundle two-state icon into a single svg file, and then use `object-position: left/right` property on the <img> tag to switch between the variants. You can also combine this with some simple css animations.
Well, there's still a compromise to be fair. It's defintely more work to manage these sprites and it's especially annoying when there's more than one state. I think it's possible to write some tool to automate it, but I haven't found one.
Boxy SVG editor comes with built-in support for creation and editing of SVG icon sprites.
You can play with a sample SVG sprite on https://boxy-svg.com/#demo-symbols. Individual icons are shown under "Defs Panel -> Symbols". To edit an icon just double-click its thumbnail. To make part of an icon recolorable, select that part and then click "Fill Panel -> Paint -> Type -> Inherit".
You could then create separate symbols which contain a recolored instance of the original symbol. The underlying markup will look something like this:
hmm, I didn't know you can use fragment identifiers in src attribute, that changes the game quite a bit. I remember looking for stuff like that, though. Not sure why I didn't anything, because it seems like it's been supported for quite a while. I only found the reuse inside svg in the same parent html document.
Fragment identifiers in "src" attribute seem to be supported by all modern browsers, but now I realized my example was wrong - you can reference <view> elements, but not <symbol> elements directly.
To make it work you would have to either replace <img src="sprite.svg#green"/> with <svg ...><use href="sprite.svg#green"></use></svg> or add views to the sprite file:
That makes a lot of sense. If you use some client-side routing (e.g. Next.js), you might be fine, because the page does not reload during navigation. But if you don't, every HTML page will contain all the SVGs increasing the HTML size unnecessarily.
P.S. I actually went ahead and changed the implementation to a separate file on my website after I saw your comment :D
It's something like this (I just quickly took this from my project, not sure if it works in this form now). This one uses the defs/use trick to reuse a path, but you can also just put two different svgs next to each other and not use the defs/use at all.
The icon:
<!-- the icon width is 2x wider, to accommodate both 26x26 variants -->
<svg xmlns="http://www.w3.org/2000/svg" width="52" height="26">
<defs>
<!-- here's the icon defined, you can basically put anything here and
mark it with an id (you can even use another svg) -->
<path id="icon" path="..."/>
</defs>
<!-- first variant with no fill -->
<use stroke="#fff" href="#icon"/>
<!-- second variant with fill, shifted by 26 (dimensions of the icon) -->
<use x="26" fill="#00ACA0" stroke="#00ACA0" href="#a"/>
</svg>
HTML:
<!-- make sure you use dimensions of the single variant -->
<img src="icon.svg" width="26" height="26" class="hover-icon">
CSS:
.hover-icon {
/* make sure that only first block of the image is visible */
object-fit: cover;
object-position: left;
}
.hover-icon:hover {
object-position: right;
}
Btw, for such simple re-colouring I'd probably rather used CSS hue shift filter or similar effect, and kept the SVG "dumb". But for having different shapes or geometric properties this approach is indeed nifty.
Yes, I do that, too. The benefit of using the sprite system is that it's pretty general, so once you have some CSS for it, it's easy to keep adding new icons. CSS filters are usually more special for each case, but I use them too (mostly for brightness and greyscale things that are repeated on multiple places, e.g. tabs or disabled state).
You might want to check out old tech articles, as sprites were a very common approach from roughly 2005-2012-ish. Lots of interesting little techniques.
Another option would be to including SVG files from SVG elements, though the whole thing is a bit cursed. I'm not 100% sure how it plays with CSS and caching
Example: svg poster - includes svg diagrams - that include svg maps (maps are generated programmatically)
It's honestly an unreliable format for anything that's mildly complex.. this poster will render differently in different browsers (and inkscape) and can't be turned into a PDF consistently. It's a mess
Actually, for interactivity you don't have to use CSS but can also use SMIL animations to set SVG (or CSS) properties for things like clicking/hovering, timed transitions, and even animation sequences. Never understood the CSS march of progress narrative when CSS just piecemeally incorporares concepts (paint servers, filters, etc) SVG had for 20 years now, and what's so great about having those available in CSS" wild unchecked syntax, especially when you'd need (or prefer) JS anyway. SVG at least can be targetted as a reasonable output format by vector drawing tools.
Ohh, interesting, I have never heard of SMIL. For this post I was thinking mostly of static styling (... and got a little carried way with interactive stuff in the diagram...) but I'll have to look into SMIL in the future.
There's an important caveat with this: It does not work cross-origin, and there is no way to make it work except for including some JS like svg4everybody. CORS does not apply.
It works out of the box with most browsers and like you said there are polyfills for older browsers. BTW the syntax with svg 2.0 is just href.
About the cross-origin issue, you mean it lacks something like a crossorigin attribute?
That's only an issue if you plan to load svgs from other websites, I don't think it's a very common usecase. If you use them at multiples places in your website, you should probably have them served from your sever anyway, if not then I guess caching is less of an issue.
I’m not confident of what is meant by “stylable”, but I’m pretty sure it’s a misnomer.
If you mean applying static styles, you can do that with any form of SVG (that is, <img> qualifies as well).
If you mean inheriting styles from the parent document, you can only do that with inline SVG (that is, <iframe> doesn’t qualify).
But by the actual usage in the article (that it’s <svg> and <iframe> but not <img>), I think what is actually meant is interactive—that you can run scripts, have :hover styles, links, things like that.
Stylable here means applying styling from the HTML files CSS file to change the colour, etc. For example:
1. changing the foreground and background of the SVG based on the web page theme or light/dark mode;
2. using the SVG in a link or button and styling the image according to the hover, pressed, etc. state, e.g. when providing custom checkbox/radio/toggle buttons.
If you’re talking about using the prefers-color-scheme media query, you can do this with any technique—<img> qualifies as well. That’s applying static styles.
If you’re talking about things like styling based on an <html class="…"> value, <iframe> doesn’t qualify: that’s inheriting styles from the parent document and you can’t do it.
For your second example: that’s about whether the SVG is interactive.
However I look at it, “stylable” is simply the wrong word.
Yet again I direct your attention to the ticks and crosses. In the article, <iframe> has been marked as stylable. But if you’re talking about controlling the styles of the SVG from the parent document, you can’t do that. So the original article cannot be using the term in the way you are.
What CSS stands for is quite immaterial in the definition of “stylable”. Especially the C. Cascading says nothing about cross-document application.
And when I speak of interactivity, I believe I’m using a term that has been employed in some of the specs and implementations to control most or all of the distinctions I’m talking about, though I have a vague feeling there was some other magic term too that I just can’t remember. I can’t trivially find the relevant definition in the SVG spec, and the HTML Standard these days says that <img src> refers to a “non-interactive, optionally animated, image resource that is neither paged nor scripted”, admittedly separating interactivity and scripting. Interactivity includes things like links and hover states.
It is actually that. If you are including an svg using <img> then you can no longer, say, change the stroke color. It also does not inherit your css from the rest of your site even on first load. Your svg is treated like any other regular png or such.
Please review my earlier comment. “Styling properties of SVG elements via CSS” is, on reflection, slightly ambiguous, but largely refers to static styling, which you can do anywhere. If you’re talking about changing things, at runtime, you’re talking about the SVG being interactive, not stylable. And heritability is, as I remarked, another different thing, which doesn’t work for <iframe>, so that can’t be what it’s talking about.
But I’m not saying you can apply styles to the inside of an image from outside; that, as I have remarked, is a different matter, about heritability—you can’t do that with any technique but inline SVG. Not <img>, not <iframe>, because it’s not cross-document.
Really interesting, am a big fan of the utility that SVG's provide, an undersung hero of the web imo. One thing I've always particularly liked is you can wrap elements inside of an <svg> tag with an <a> tag, useful in the battle against a "square" web!
For the particular purpose mentioned in the article another solution is to use CSS' `mask-image`/`-webkit-mask-image` and fragment identifiers in a single SVG that get swapped between hover/regular states. Avoids any inline markup and as a bonus the element color is stylable via the parent page's CSS, albeit one isn't manipulating the inner SVG (though in the OP's case it's a static shape).
The `<use />` tag introduces another dimension to the analysis: "Is a first-class citizen of the web". Most resources can be included from anywhere and the serving and the hosting pages can limit that universality but the web defaults to "open". SVG's `<use>` is more limited. Cross-site `use` doesn't always work (and there's no way to opt-in to it). `data:` URLs were just removed for some reason (there are mumbles about security but no explanations why this one tag is so much worse for security than say `iframe srcdoc`).
All that said, if you're doing an include from the same host as the parent page, yes, `use` absolutely does tick all three boxes!
I went the rabbit hole of exploring SVG "decimal precision-related" glitches in browser implementations and to my grief I must confirm that there really are blatant cross-browser issues. It's fact that my tests went a bit over-the-top with dimensions -- who would make 1e9 or 1e-9 wide viewBox in real world anyway? -- but since refraining from doing so is not discouraged in the specs, one would expect it would scale (pun intended) at least few orders of magnitude. The results for my particular testcase showed that "safe" range was only between 2e3 and 2e5: [1].
> who would make 1e9 or 1e-9 wide viewBox in real world anyway?
Back in about 2008 I made an SVG diagram showing the height of various satellite orbits above earth, specifying the SVG at 1:1 scale - making the image 84,000 km wide.
Sadly a load of file viewers choked on it, so I had to settle for a downscaled version. It seems the 'scalable' in 'scalable vector graphics' only goes so far.
Ha, nice! I secretly hoped someone would mention their real-world usage of "ridiculously" large SVG dimensions, so thanks for the reference!
Your story implies there actually were some viewers that could handle it correctly? Could you recall more details what were they? (My testing was pitifully limited to current browsers only, but I know there must be vast amount of other viewers.)
And if I may ask, did you map one SVG "point" to some length unit (e.g. meter, so getting 84e6 wide wiewBox), or did you assume 90 DPI "pixel" mapping to ~0.2822 mm?
However the browsers don't crash or run out of memory, so they've got that going for them. And if you embed the image in a web page with <img src='84km.svg' width=1000 height=1000> chromium almost manages to display it.
SVG lets you specify sizes in a bunch of different units, but there's actually a fixed ratio between them - in SVG, 1mm means is 3.78px regardless of your display or printer's DPI.
So I didn't scale mm to SVG's arbitrary length units - but the standard did.
So at this point we don't know about any viewer capable of handling Earths orbit sized SVG? That's sad.
> However the browsers don't crash or run out of memory
Good news for your sample. Yet in some browsers there prevail some open issues, just the limits are now farther. For example feeding this SVG to my Firefox almost instantly exhausts my RAM and makes the browser window unusable for a while:
I tried to make a daily timeline in SVG where 1 unit = 1 second. There are 86400 seconds in a day. Both Firefox and Chrome did not render the image properly, so I had to scale the numbers down too. What a shame.
Also, browsers seem to render svg circular arcs using bezier curves. At high zoom levels there can be quite a discrepancy between the actual curve (drawn using lots of straight line segments, say) and what the browser renders for a circle.
Do they? I thought this is more issue on the source code side, rather than implementation: this is actually my pet-peeves, that most SVG *authoring tools* never output circular arcs and always use cubic béziers approximations instead. So we nearly ever see real circles or their segments, even though authors use them in their designs all the time.
It was a few years ago and I'm unable to reproduce it. Circles and circle approximations from straight lines seem to coincide exactly in Firefox and Edge now.
I was generating diagrams using my own code so I'm positive they were circular arcs. Tangents weren't tangent and it took me a while to realise that the problem was the browser rendering something that wasn't quite a circle. I assumed it was a bezier approximation but I didn't verify that. Whatever it was it seems to be fixed.
Another thing I've noticed is that Chrome doesn't seem to render SVGs with anti aliasing (at least not always?). This makes SVGs unsuitable for lots of kiosk-style systems, where you often have Chrome showing a web page on a relatively large low resolution screen.
I like using external svg files for icons because they are tiny and cacheable. I get around the colorization problem by creating different icon files for each color. In practice, I only have a small number of colors to worry about. So:
Seeing that svg is text, enabling gzip compression on server will certainly help with reducing size; especially if using lots of inlined repeating svg elements (like icons, glyphs, etc). I also imagine SPA that compile to one index.js file can massively benefit from inlining svg + server compression (also, very cacheable!)
SVG often includes raster images? That's very surprising to me. I can see some use cases here and there, sure, but using a vector format to 'often' include raster images... i dunno.
Thousands of XML elements is the ideal case, compresses extremely well.
I think there are lots of solutions if you allow a JavaScript dependency. In the article, the author demonstrates dynamic 'styling' by just swapping out an image - just like we used to do it back in the 20th century! You could fix the caching problem by dumping your SVG contents into localStorage.
Like it injects/modifies the styles of pages willy-nilly? The beauty of browsers is that you're fully able to do that, but seems like a great way to just have a broken browsing experience all the time...
In my case, i have the standard browser dark preference active and the website obliges and shows a broken dark theme. If i instead use the style-injecty version such as dark reader, it actually fixes the website's broken dark theme and i can see the graph. So in this case, it is completely the website's fault.
Darkreader does a really good job of preserving visibility in most cases, and is available on both mobile and desktop browsers. Definitely reconnect checking it out.
For me (Firefox on macOS, also tested with Chrome on macoS), the site's dark theme has a purple background for the diagram which makes it readable even though the background is black.
However, the SVG seems to get all its color from CSS; the color is not part of the SVG itself. Maybe that's not working in your browser?
Huh. I'm the OP, and I do have a dark mode that respects `prefers-color-scheme: dark` -- or at least, it works for me (tm). Would you mind sharing details about your dark mode theme? Is it a third party extension or maybe a browser I haven't tested?
I'm on Windows and in the system-level settings app, there's a toggle for dark mode. When I turn that on, then `prefers-color-scheme: dark` starts matching. There are zero third-party extensions or styles here, and my browser is Chromium 118.
Ohhh interesting. To anyone hitting this, I'm curious what specific browser you're using - I thought it was available ~everywhere now? https://caniuse.com/css-nesting
I can't replicate on mine. If this is due to nested styles, I think you are behind on your software updates :). But also, maybe I need to hold off a bit longer before moving to nested styles.
According to a forum post [1], e.g. iPad Mini 4 was discontinued March 2019 and is stuck on iOS 15, which doesn't support nested styles. Perhaps the issue is that people want to continue using old tablet devices that are no longer getting OS updates?
Or just use any modern DOM-manipulating JavaScript framework like React - in effect putting an `<svg>` tag in very cacheable JavaScript. <div style={...}><p className="...">...</p><svg viewBox="..."><g fill="...">...</g></svg></div>, whichever.
It's a first class citizen, put it in a React Component, anything goes. Cacheable, stylable, and dimensional.
Can't you say that about anything in HTML? Like, imagine you had a huge `<head>` tag that contained a bunch of stuff, but it's essentially the same (except for, like, the title) for all documents. Don't you wanna do this?
Where the `<<< include ... >>>` is a pretend bit of HTML that makes the browser fetch that from somewhere else. A preprocessor, more or less.I realize this is what templating languages are for, but if this happened on the HTML layer, the browser could do way better caching.