Smooth background change

Question:

I’m making a website where the background will have to change every 10-20 seconds.

I managed to achieve this by getting an image from the server and changing the css style of the page. But because of this, when changing the background, the background briefly turns white. I think this is due to the fact that the image is not received instantly.

Does anyone know how to fix this?

Repl link:

https://replit.com/@KAlexK/GetHelp?v=1

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <title>Site</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    Hello world!
    <script type="text/javascript" src=" {{url_for('static', filename='script.js')}} "></script>
</body>
</html>

script.js

const randint = function(a, b) {
    return Math.round((Math.random() * (b - a)) + a);
}

const changeBackground = function(id, random=false) {
    if (random) {
        const r = randint(1, 6)
        document.body.style["background-image"] = `url(static/backgrounds/bg_${r}.png)`;
    } else {
        document.body.style["background-image"] = `url(static/backgrounds/bg_${id}.png)`;
    }
}

setInterval(changeBackground, 10000, null, true);

style.css

html {
    width: 100%;
    height: 100%;
}

body {
    margin: 0px;
    background: url(backgrounds/bg_1.png) no-repeat center center fixed;
    background-size: cover;
    transition: background 2s;
}

File system:

image

The server takes some time to get those images, so the solution would be to preload the images.

const preloadImages = function() {
    for (let i = 1; i <= 6; i++) {
        const img = new Image();
        img.src = `static/backgrounds/bg_${i}.png`;
    }
}

Website link: gethelp.kalexk.repl.co

4 Likes

Thank you for your reply!

Your code in most cases helps to avoid unnecessary requests to the server, but sometimes still requests are sent to the server and the background becomes pure white.

3 Likes

I would caution you that sending multiple images a minute to users indefinitely will use up a considerable amount of your outbound data usage if someone forgets to close their tab.

3 Likes

As a result, I decided to abandon the changing background. Thanks to everyone who took part in the discussion!

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.