1

I recently started learning HTML and JS and got stuck at this point. I am using "cataas" to update a new image but every time I reload the page, nothing changes.

function loadCatPicture() {
  var img = document.getElementById('cat-picture');
  img.src = 'https://cataas.com/cat';
};

window.onload = function() {
  loadCatPicture();
};
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h1>Cats Sleep Anywhere</h1>
  <p>
    Cats sleep anywhere, any table, any chair.<br> Top of piano, window-ledge, in the middle, on the edge.<br> Open draw, empty shoe, anybody's lap will do.<br> Fitted in a cardboard box, in the cupboard with your frocks.<br> Anywhere! They don't care!
    Cats sleep anywhere.<br>
    <br>
    <img id="cat-picture">
    <b>Eleanor Farjeon</b></p>
  <p></p>
</body>

</html>

2 Answers2

1

Your browser is probably just caching the image response from cataas.com.

Per the answers to this SO question, you can just tack on some harmless GET parameters to the request URL that will be ignored by the server but ultimately trick your browser into not caching the response:

function loadCatPicture() {
  var img = document.getElementById('cat-picture');
  img.src = 'https://cataas.com/cat?ver=' + (new Date().getTime());
};

window.onload = function() {
  loadCatPicture();
};
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h1>Cats Sleep Anywhere</h1>
  <p>
    Cats sleep anywhere, any table, any chair.<br> Top of piano, window-ledge, in the middle, on the edge.<br> Open draw, empty shoe, anybody's lap will do.<br> Fitted in a cardboard box, in the cupboard with your frocks.<br> Anywhere! They don't care!
    Cats sleep anywhere.<br>
    <br>
    <img id="cat-picture">
    <b>Eleanor Farjeon</b></p>
  <p></p>
</body>

</html>
esqew
  • 34,625
  • 25
  • 85
  • 121
0

it is possible that your browser is caching the image. Since the image URL doesn't actually change and just the actual image instead. to see a change in your code you would have to clear your browser's cache. In Chrome it's as easy as clearing your history ;)

Nik Hendricks
  • 262
  • 4
  • 24