Maxim Bernard
Maxim Bernard

Reputation: 307

Weird behaviour of <iframe> when page is reloaded

I have three simple HTML files in the same directory :

index.html

    <html>
        <head>
            <title>Page 1</title>
        </head>
        <body>
            <iframe src="page2.html"></iframe>
        </body>
    </html>

page2.html and page3.html (about the same content)

    <html>
        <head>
            <title>Page 2</title>
        </head>
        <body>
            This is the content of page 2
        </body>
    </html>


    <html>
        <head>
            <title>Page 3</title>
        </head>
        <body>
            This is the content of page 3
        </body>
    </html>

index.html contains an <iframe> that points to one of the two other HTML files.

When I load index.html for the first time, it works as expected and prints "This is the content of page 2". But when I change the src attribute to "page3.html", and reload the page, nothing changes. It keeps telling me "This is the content of page 2", even though it's supposed to load page 3 instead.

But then, when I close the tab and reopen the page (index.html), it works and prints "This is the content of page 3". But when I change it back to page2.html, it sticks to page 3.

That's weird. I guess the browser is caching the page, or something like that.

When I add :

<script>
    document.write(document.querySelector("iframe").src);
</script>

Then, it prints the correct file location. (But the content of the iframe is still wrong.)

That means that even though the browser detected that the file has changed, it doesn't even reload the iframe when the page is reloaded.

What could cause this strange behavior ? And how can I fix it ?

Thanks.

P.S. Tested using Firefox 29.

P.S. (2) All the files are on my PC, I'm not fetching them on a distant server.

Upvotes: 4

Views: 330

Answers (2)

Tarun
Tarun

Reputation: 651

Try adding something like:

 document.getElementById(FrameID).contentDocument.location.reload(true);

This forces the iframe to reload every time the page is reloaded.

EDIT: I tried this out using Chrome and it worked fine, even without the script.

Upvotes: 2

Yonatan Ayalon
Yonatan Ayalon

Reputation: 2045

If you're planning on changing this Iframe frequently, I would create the iframe dynamically, via Javascript (important to mention - you'll loose FF caching on the iframe):

HTML Code:

<!doctype html>
<html>
    <head>
        <title>Page 1</title>
    </head>
    <body>
        <div id="iframe_wrapper"></div>
    </body>
</html>

Javascript Code:

document.addEventListener("DOMContentLoaded", function(event) {
    var iframeWrapper = document.getElementById("iframe_wrapper");
    var iframe = document.createElement("iframe");
    iframe.src="http://www.bing.com/";
    iframe.width = "400";
    iframe.height = "400";

    iframeWrapper.appendChild(iframe);
});

Upvotes: 0

Related Questions