How to preload css :hover background-images

Viewed 4819

I have multiple background-images that change on hover.

Example:

.class1 {
    background: url(/img/img-1.jpg) no-repeat top center;
}
.class1:hover {
    background: url(/img/img-2.jpg) no-repeat top center;
}

The images flicker now, as they are loaded the second you hover over them. I've tried using sprites, but that doesn't work, as the images change size for mobile devices.

Any ideas? Could be css or jquery, doesn't matter much

6 Answers

I've used the following technique:

.class1:hover,
.class1-hover-preload {
    background: url(/img/img-2.jpg) no-repeat top center;
}

and added the elements with -hover-preload classes to my html into a container with 0 height. This way, I keep the path definition for preloaders in the same place as the elements (CSS itself) so that if they are changed for hover, preloading won't get broken.

The best way I found that works (tested in Firefox and Chrome on Mac), is to paint the image with opacity: 0, like this:

&::before {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    opacity: 0;
    pointer-events: none;
    background: url(image.png);
}

Bit it's still not 100% reliable. In Safari it flickers quite much still.

Related