Smooth background change


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:


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


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)["background-image"] = `url(static/backgrounds/bg_${r}.png)`;
    } else {["background-image"] = `url(static/backgrounds/bg_${id}.png)`;

setInterval(changeBackground, 10000, null, true);


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:


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:


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.


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.


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


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