Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

javascript - Reloading the web page does not update img.src

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>
question from:https://stackoverflow.com/questions/65879205/reloading-the-web-page-does-not-update-img-src

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...