How to prevent a background image flickering on change

HTML

I try to change a image via JavaScript. But the image is flickering on change.  I've tried some different solutions but it doesnt seem to prevent the flickering.

<img src="/my-image.png" id="image" alt="Test image" />
<button class="change-image">Change image</button>

JavaScript:

$('.change-image').on('click', function () {
    $('#image').attr('src', '/my-other-image.png');
})
CSS JavaScript Question created: 2020-07-11 07:31 Gammi

5

This happens because the new image source need to be loaded via a HTTP-Requests. So the image will be “empty” for a short while which forces the flickering. Once the new image is loaded by the browser, the image will be displayed in the browser. 

There are different approaches to prevent this behavior. All solutions focusing a logic where the new image is preloaded in the browser.

You could preload the image via DOM adding a hidden element into your HTML Document:

<img src="/my-other-image.png" style="display:none" />

This issues also came up on css animations. Sometimes a background is flickering on mobile devices which can be stoped by hidding  the backface visibility of your image or image container: 

-webkit-backface-visibility: hidden;
-moz-backface-visibility:    hidden;
-ms-backface-visibility:     hidden;

Another solution is to use sprite images. This is a common way to have only one image to combine multiple images into one image file on your website. This could be use for small images like icons. Or simply use fonts for displaying your icons. 

answered 2020-07-11 07:41 codeBrother