Skip to content

Check if iframe content has been loaded already

I am trying to check if the iframe src has been already added the first time so that it does not load it again in the second time. The iframe is activated with the function given below, I am using jQuery to check this. Unfortunately the console.log("loaded"); gets called every time the function is triggered. What am I doing wrong?

    <iframe id="iframe_01" style="
   position: fixed;
   margin: auto;
   height: 100%;
   width: 100%;
   overflow: hidden;
   z-index: 10;
   display: none;
   ">
    </iframe>

<script>
function Activate_iFrame() {

    //iframe start
    let iframe_01 = document.getElementById("iframe_01");

    iframe_01.style.display = 'Block';

    if ($("#iframe_01").find("iframe").contents().find("body")) {
        console.log("loaded");
        iframe_01.src = "LINK TO WEBSITE";
    }
}
</script>

Answer

You need to add a flag to your code to stop the test running a second time

let iframeLoaded = false;

function Activate_iFrame() {

    //iframe start
    let iframe_01 = document.getElementById("iframe_01");

    iframe_01.style.display = 'Block';

    if (!iframeLoaded &&$("#iframe_01").find("iframe").contents().find("body")) {
        console.log("loaded");
        iframeLoaded = true;
        iframe_01.src = "LINK TO WEBSITE";
    }
}