Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get new lorem picsum on button click

I write this line of javascript multiple times(on a button click). The problem is that i get a random image first time and then it doesn't change anymore. Any help, please?

document.getElementsByTagName("body")[0].style.backgroundImage = "url(https://picsum.photos/200/300/?random)";
    
like image 281
Alexandru Necula Avatar asked May 02 '18 11:05

Alexandru Necula


2 Answers

Most probably the response is getting cached.

You can ensure that a fresh requests is created every time by appending an inconsequential time value as

document.getElementsByTagName("body")[0].style.backgroundImage = "url(https://picsum.photos/200/300/?random&t=" + new Date().getTime() +")";
like image 166
gurvinder372 Avatar answered Oct 25 '22 05:10

gurvinder372


This will work better. You only get ONE redirect when you get the CSS - the browser caches the result. This one will keep the https://picsum.photos/200/300/?random from being cached by the browser. The getDate() returns number of milliseconds since 1970

<button 
onclick='document.getElementsByTagName("body")[0].style.backgroundImage = 
"url(https://picsum.photos/200/300/?random&rnd"+new Date().getTime()+")"' 
type="button">Click</button>
like image 42
mplungjan Avatar answered Oct 25 '22 05:10

mplungjan