How to fix SVG background flickering once on hover

How to fix SVG background flickering once on hover

1. Problem with SVG flash/ flicker

If you have a button with an SVG background that also has an SVG background for its hover. When you hover over it for the first time after the page loads, there is a flicker, but there is no flicker on any subsequent hover.

The demo page is here: https://codepen.io/Lifeni/pen/MWKQRzR.

svg

The specific performance is that when the mouse moves to the button on the left, the SVG picture keeps flashing.

2. Root cause and how to fix SVG flash/ flicker problem

First approach: This is because hidden elements/assets are not loaded (inactive selectors or display: none, etc). You have to preload it manually.

.minus {
  background: url(https://www.svgrepo.com/show/294589/shuffle-random.svg);
  background-size: cover;
  border: 0;
  display: block;
  height: 20px;
  width: 20px;
}

.minus:hover {
  background: url(https://www.svgrepo.com/show/240096/shuffle-random.svg);
}

body:after {
  /* display: none -- does not work anymore due to latest optimizations.*/
  display: block;
  overflow: hidden;
  width: 0;
  height: 0;
  content: url(https://www.svgrepo.com/show/240096/shuffle-random.svg);
}
<button class="minus"></button>

Second approach: Use a tiled sprite as (one) image and just move the background position on hover. Or just load both at once.

.minus {
  background: 
    url(https://www.svgrepo.com/show/294589/shuffle-random.svg),
    url(https://www.svgrepo.com/show/240096/shuffle-random.svg);
  background-size: cover;
  background-position: 0, 20px;
  background-repeat: no-repeat;
  border: 0;
  display: block;
  height: 20px;
  width: 20px;
}

.minus:hover {
  background-position: 0;
}
<button class="minus"></button>