Search code examples
htmlcssangularcss-animations

How do I avoid flickering in slide show made with CSS animations?


I've made a simple slide show with CSS animations in Angular. It works well, but I encounter white flickering between images, which depends on image loading, I suppose. Is there a way to avoid this flickering and make it seamless?

CSS file

.bg{
    background-size: 100%;
    background-repeat: no-repeat;
    background-attachment: fixed;

    height: 100vh;

    animation: BgAnimation forwards;
    animation-duration: 8s;
    animation-iteration-count: 1;
    animation-timing-function: linear;
    animation-direction: normal;
}

@keyframes BgAnimation {
    0%   { background-image: url(../../assets/outro/1.jpg); }
    33%  { background-image: url(../../assets/outro/2.png); }
    66%  { background-image: url(../../assets/outro/3.jpg); }
    100%  { background-image: url(../../assets/outro/4.png); }
}

HTML file

<div class="bg"></div>

Solution

  • The angular way is to use ngOptimizedImage directive in your code then convert the code to work with image tags, instead of background image!

    ngOptimizedImage getting started

    ngOptimizedImage docs

    We can use the pirority attribute to increase priority of the resource loading!

    <img ngSrc="cat.jpg" width="400" height="200" priority>
    

    You can use the below CSS, to preload the images (Since body tag is displayed on first load, which will immediately load the images mentioned in content), before the animation starts

    body {
        position: relative;
    }
    
    body:after {
        content: url(https://placehold.co/600x400/000000/FFFFFF/png) url(https://placehold.co/600x400/FFFFFF/000000/png) url(https://placehold.co/600x400/000000/FFFFFF/png) url(https://placehold.co/600x400/FFFFFF/000000/png);
        height: 0px;
        width: 0px;
        visibility: hidden;
        position: absolute;
        top: -1000px;
    }
    

    You can encode the images to base64 so that they are always present in the HTML, but note this increases the size of your HTML page (waste of size), but this means, the image is immediately available!

    background-image: url("data:image/png;base64,iVBORw0KGgoAAAANS...");
    

    base64 image encoder