Jesús López
Jesús López

Reputation: 9241

How to preload svg sprites?

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

.

Upvotes: 16

Views: 7027

Answers (1)

42yeah
42yeah

Reputation: 91

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">

Upvotes: 1

Related Questions