8
votes

I have a svg sprites file icons.svg like this:

<?xml version="1.0" encoding="utf-8" ?>
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">

  <symbol id="twitter" viewBox="0 0 512 512">
    <path d="..some path data here..."></path>
  </symbol>

  <symbol id="facebook" viewBox="0 0 512 512">
    <path d="..some path data here..."></path>
  </symbol>
</svg>

That I reference from web page body:

<svg>
    <use xlink:href="/images/common/icons.svg#twitter"></use>
</svg>

I would like to preload icons.svg to avoid flickering. How to do that?

I tried to add link rel preload to head:

<head>
    <link rel="preload" href="/images/common/icons.svg" as="image" type="image/svg+xml"/>
</head>

But it doesn't work. I see icons.svg loaded two times on Chrome developer tools, and the following warning:

The resource http://localhost:57143/images/common/icons.svg was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate as value and it is preloaded intentionally

.

1
@enxaneta. I don't fully understand your comment. Icons are shown without problem, I just want to preload them.Jesús López
I think this is a Chrome bug - I'm seeing the same issue in Chrome. It seems that the disk cache is being used on the second request in my scenario, but it's possible that's circumstantial - ie my 2nd request isn't invoked in parallel with the 1st, so the cached result from the 1st can be used. And FireFox doesn't support preload, making it harder to verify this is a browser bug.crimbo
I submitted a Chromium bug for this: bugs.chromium.org/p/chromium/issues/detail?id=1065069crimbo
Looks like if you remove as="image" type="image/svg+xml" the svg is preloaded.allcaps
I'm having the same problem. If I put a display:none <img at the top of <body, the file gets loaded twice. If I preload it as you have, it gets loaded twice. If I follow @allcaps advice and preload it without the as \ type declarations, if only gets loaded once - but when the first icon requests it, not where the preload line is. Did you find a solution @JesúsLópez?Codemonkey

1 Answers

0
votes

Maybe try using prefetch instead if you are not using it right away? it will still be loaded.

  <link rel="prefetch" href="/images/common/icons.svg" as="image" type="image/svg+xml"/>

As it is preloaded as image, using the <img> tag can suppress this warning. Adding an invisible image using this svg somewhere should work:

  <img src="/images/common/icons.svg" style="display: none">