0

I have the following code, that checks the iFrame content width every 0.1 seconds. This code works, but I don't think it is best practice.

Here is my code

function iframeLoaded() {
    var iFrameID = document.getElementById('appframe');
    if (iFrameID) 
    {
        iFrameID.height = ''; 
        if (iFrameID.height != iFrameID.contentWindow.document.body.scrollHeight + 'px') 
        {
            iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + 'px';
        }
    }
}

setTimeout(iframeLoaded, 100);

and the HTML

<iframe src='https://google.com' frameborder='0' scrolling='no' id='appframe' onload='iframeLoaded()'></iframe>

Would the best solution be to check if the iFrame height has changed every 0.1 seconds, and only then adapt the size of iframe height if a change has been noticed.

As now, the code is adapting the height, even if they detect no change in iFrame height.

Peter B
  • 22,460
  • 5
  • 32
  • 69
BCLtd
  • 1,459
  • 2
  • 18
  • 45
  • Possible duplicate of [Resizing an iframe based on content](https://stackoverflow.com/questions/153152/resizing-an-iframe-based-on-content) – Peter B Nov 16 '18 at 14:34
  • `that checks the iFrame content width every 0.1 seconds` ... from your code, I can say you're checking only once after 0.1s, not every `0.1s` What are you actually trying to acomplish? – Ionut Necula Nov 16 '18 at 14:34

1 Answers1

0

You can add a event listener:

var iframeWindow = document.getElementById('myiframe').contentWindow; $(iframeWindow).on('resize', function(){ //... });

I.Manev
  • 709
  • 7
  • 23