How do I clear iframe's cache or force it to reload?

Viewed 32

I am using one iframe to display multiple videos, one at a time, by changing the value of its src attribute.

Users can close the video, which actually hides the iframe behind an overlay.

Next time,

  1. the user chooses another video on a slideshow
  2. the iframe's src changes to the new one
  3. the user clicks a Play button\
  4. the overlay becomes invisible
  5. the iframe shows up and plays the new video.

The issue I am facing is that between step 4 and 5, users always see the image of the old video momentarily before seeing the new one, which is not good.

I guess that is because the iframe is still loading the new video, during which time it still keeps the old video.

I can think of two ways to solve it:

right after every time the src changes in step 2:

  1. force the iframe to load the new video. The change of src is prior to playing the video, so when the video plays, the iframe should have already abandoned the old one for some time.

  2. "clear" the iframe so it is empty now, and should display a blank screen prior to finishing loading the new video.

But I don't know how to achieve either... Is there a function in iframe like

let iframe = document.getElementById("iframe_id");
iframe.clearCache();
// or
iframe.reload();

?

(I maybe able to desctroy the iframe HTML element every time and recreate it, but it seems costly and not very elegant...)

Thanks in advance!

1 Answers

I looked into it, and I adapted this (example 1) example. Here are the changes I made

Please look at the link for complete code. What follows are strictly modifications for simplicity

  <input type="button"
         id="hider"
         value="Hide"/>
<script>
    function reload() {
      console.log(document.getElementById('iframeid').src);
      // if we are currently watching Bob1, we will load Bob2
      if (document.getElementById('iframeid').src.includes("Bob1"))
        document.getElementById('iframeid').src = 'Bob2.webm';
      else
        document.getElementById('iframeid').src = 'Bob1.webm';
    }

    //Wait for reload, and then show iframe. This is the money
    document.getElementById('iframeid').onload = () => document.getElementById('iframeid').style.display = "block"

    btn.onclick = reload;

    //when we hit the hide button, hide our iframe
    hider.onclick = () => {
      document.getElementById('iframeid').style.display = "none";
    };
</script>

To use this, you should first hit the hide button and then press the refresh.

I changed the refresh button to switch between two videos, and then after it has loaded, then and only then should it show itself. This at least for me avoids your issue.

You will need to change this example to your usecase, such as

document.getElementById('iframeid').onload = () => document.getElementById('iframeid').style.display = "block"

to the display that your iframe uses.

Related