Prevent Image Caching - Javascript

Viewed 45

This function is supposed to grab a random image from the url everytime its called

function grabImg(){
    var img = document.createElement('img');
    img.src = 'https://picsum.photos/200/300';
    document.getElementById('flex-cat').appendChild(img);
}

And display it in the div below

<div class="container-1">
    <h2>Image Grabber</h2>
    <button class="btn btn-success" onclick="grabImg()">Grab Image</button>
    <div class="flex-box-container-2" id="flex-cat"></div>
</div>

Initially when the button is clicked, it calls the function and displays an image fine. However when the button is clicked on multiple times, instead of displaying different random images, the same image which was shown the first time keeps being displayed.

Any tips on how to prevent this?

1 Answers

Using picsum documentation, see Advanced Usage, you can request multiple images of the same size in your browser, add the random query param to prevent the images from being cached. Then you can randomize the number using a helper function, then concatenate using string literal => img.src = https://picsum.photos/200/300?random=${randomRange(10000)}.

EDIT: To make it truly random, track the random numbers created with the helper function using an array. If the value is present in the array already, then run the randomImage method again, else push the value into the array for tracking purposes and return the random value.

const arr = []
function randomImage() { // get a random number 
  let num = ''
  let tempRan = Math.random()
  if(!arr.includes(tempRan)){
    num = tempRan
    arr.push(num)
  }else{ 
    randomImage()
  }
  return arr[arr.length-1]
}

function grabImg() {
  var img = document.createElement('img');
  img.src = `https://picsum.photos/200/300?random=${randomImage()}`;
  document.getElementById('flex-cat').appendChild(img);
}
<div class="container-1">
  <h2>Image Grabber</h2>
  <button class="btn btn-success" onclick="grabImg()">Grab Image</button>
  <div class="flex-box-container-2" id="flex-cat">
  </div>
</div>

Related