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: