Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we cache inline SVG in Browsers?

SVGs have been around for years due to its scalability and it is long-familiar that the benefit of inline SVG is one can manipulate it with CSS and JS, and when we want to repeat the same SVG over a html document, then we can use the <use> tag to reference the original element. Furthermore, inline SVGs could also reduce the number of HTTP requests.

However, many articles suggest (without explaining the details) that while we use inline SVG to save HTTP request, it is no longer cacheable by a browser as a separate subject, which means it is not reusable across the pages.

As I happen to use inline SVGs extensively for a project, I would like to know exactly how inline SVG (the renowned html5 element, which is a w3c recommendation) can be cached in browsers whilst using SVGs with <img> tag or background-image are cacheable.

If DOM is cacheable, then why can't the SVG DOM ? (which builds upon and is compatible with DOM Level 2. Ref: https://www.w3.org/TR/SVG/svgdom.html)

So far, the solution I came up with cachebility is to use Data URI scheme (Also Ref: Optimizing svgs in data uris ) But by doing so, it loses the ability to deal with CSS and JS for styling and manipulation.

A few examples around the web suggest the use of JS to load cacheable resource or by replacing placeholder elements such as <object> tag, as well as using localStorage, CacheStorage and Service Worker. But I still need some guide lines to get started to achieve an ideal solution.

Could someone shed me some light please?

-

-

-

Ref: Caching SVG Sprite in localStorage

Ref: Inline SVG and caching

Ref: SVG ON THE WEB

Ref: Do Inline SVGs Weigh Down Websites?

like image 221
Aung Myo Linn Avatar asked Jun 15 '16 10:06

Aung Myo Linn


1 Answers

Basic HTTP caching works based on URLs, and it is “all or nothing” - you can instruct the client to either take the whole resource from cache, or to reload it completely.

Now, by “inlining” your SVGs, you are making them part of the HTML document - they are not external resources any more, that could individually be checked for whether they can be taken from cache or need to be reloaded.

So, if you have three HTML documents that all have the same SVG image inlined, the code of the image will be loaded three times - because it is part of the three HTML documents.

Whereas, if the image was embedded as an external resource (as img, background-image, object, …), it would be loaded only once, on the first of those three HTML pages the browser loads. On the other pages, it will recognize, “hey, that external resource with this particular URL is in my cache already - no need to load it again.”

like image 68
CBroe Avatar answered Nov 12 '22 02:11

CBroe