Yoda Yoda - 1 month ago 17
CSS Question

iOS browser - iFrame jumps to top when changing css or content using javascript

This problem seems to have been around forever. Under some specific circumstances, iOS browsers surface this frustrating bug.

The issue:

If you have a webpage which contains an iFrame and you are modifying the iframes content document programatically, the iframe will jump to the top of the page. However, this only happens if the page, before the DOM manipulation, is beyond some height, typically this seems to be a length greater than twice the length of the viewport.

This issue appears regardless of whether you are modifying the DOM structure or changing style properties.

This bug is only present on iOS, including the latest release as of this time (9.2)

Answer

Problem description:

The issue appears to be that browsers in iOS (including chrome as it uses the same rendering engine) are not correctly calculating the height of iFrames, this is causing jumping behaviour when repaints occur on the browser.

The solutions:

Solution A: Adding the following code to the iFrame stylesheet resolves the issue in most cases, though scrolling for drag events etc may present problems with this approach.

html, body {
    height: 100%;
    overflow: auto;
    -webkit-overflow-scrolling: touch;
}

Solution B: When the iFrame content has rendered, you should calculate the height of the iFrame content then set that value explicitly on the iFrame element using an inline style in javascript. This value needs to be updated as content is modified or added in the iFrame, you must ensure the height is always correct to prevent the jumping from reoccurring.

This presents challenges when dealing with third party plugins and widgets which alter the page with no obvious callbacks. The best case for dealing with this for now is the use of mutation observers.