If you use only JavaScript, I would suggest the following:
Rename background files with names with sequential numbers:
fundo1.jpg
fundo2.jpg
fundo3.jpg
fundo4.jpg
Then after your header
, call the script:
<script>
var fundo = [1,2,3,4][Math.floor(Math.random()*4)];
var e_header = document.querySelector("header");
e_header.style.backgroundImage = "url(fundo"+fundo+".jpg)";
</script>
Note: Because images will be called by random numbers, it may be that the same image is loaded after a new page load. If avoiding this is of importance , you can create a localStorage
to prevent the same image from being loaded again at the next page load. For this the code changes:
<script>
function randFundo(){
var fundo = [1,2,3][Math.floor(Math.random()*3)];
!localStorage.fundo ? localStorage.fundo = fundo : 0;
return localStorage.fundo == fundo
?
(localStorage.fundo = fundo+1)
:
(localStorage.fundo = fundo);
}
var e_header = document.querySelector("header");
e_header.style.backgroundImage = "url(fundo"+randFundo()+".jpg)";
</script>
SIMULATION
Code only for test without refresh on page. Use one of the codes
above.
In the example below, click the Refresh button to change the background of div
:
var localstorage = { fundo: "" };
function atualizar(){
var e_header = document.querySelector("header");
e_header.style.backgroundImage = "url(http://dvdteste.hospedagemdesites.ws/imagem"+randFundo()+".jpg)";
}
function randFundo(){
var fundo = [1,2,3][Math.floor(Math.random()*3)];
!localstorage.fundo ? localstorage.fundo = fundo : 0;
return localstorage.fundo == fundo
?
(localstorage.fundo = fundo+1)
:
(localstorage.fundo = fundo);
}
window.onload = atualizar;
header{
display: block;
width: 300px;
height: 200px;
background-color: yellow;
background-size: cover;
float: left;
}
<header></header>
<input type="button" value="Atualizar" onclick="atualizar()" />