Responsive iFrame

Responsive iFrame

After extensive research and numerous tests, I finally discovered a nice way to make iframes entirely responsive.

See my example of responsive iframe.

I spent some time experimenting with the window.requestAnimationFrame() method, which instructs the browser to perform an animation and requests it to call a specified function to update the animation before the next repaint. This method repeatedly calls itself to render each frame, with the frequency generally matching the display’s refresh rate.

Using requestAnimationFrame(), I was able to respond to every layout change immediately. However, I still needed a reliable way to determine the content height of the iframe. This was resolved by pairing it with the getComputedStyle() method, which returns an object containing the values of all CSS properties of an element, including any resolved computations.

<script>
function fit() {
    var iframes = document.querySelectorAll("iframe.iFrameFit")
    for(var id = 0; id < iframes.length; id++) {
        var win = iframes[id].contentWindow
        var doc = win.document
        var html = doc.documentElement
        var body = doc.body
        var ifrm = iframes[id]
        if(body) {
            body.style.overflowX = "hidden"
            body.style.overflowY = "hidden"
        }
        if(html) {
            html.style.overflowX = "hidden"
            html.style.overflowY = "hidden"
            var style = win.getComputedStyle(html)
			ifrm.width = "100%"
            ifrm.height = parseInt(style.getPropertyValue("height"))
        }
    }
    requestAnimationFrame(fit)
}
addEventListener("load", requestAnimationFrame.bind(this, fit))
</script>

The above script automatically fetches all iframes from the DOM that have the .iFrameFit class assigned. It then retrieves and uses the pre-calculated style values for width and height from document.getComputedStyle(iframe), ensuring a pixel-perfect size for each element.

So, add the above script in the header of your main page that calls the iframe, and then call the iframe in your page body:

<iframe src="iframe.htm" frameborder="0" scrolling="no" class="iFrameFit"></iframe>

It’s important to note that this solution doesn’t work for Cross-Origin Requests on Server (CORS). No solution can, without employing a two-way communication strategy like IFrameResizer, as JavaScript cannot access the DOM of an iframe from a different origin.

External Resources:
IFrameResizer
Window: requestAnimationFrame() method
Window: getComputedStyle() method