I've tried different solutions and nothing worked properly for me. In the end I achieved with the following script in my document's <head>
:
<script>
document.addEventListener('DOMContentLoaded', function(){
var iframe = document.getElementById("YourIframeId");
iframe.style.position="fixed";
iframe.style.visibility="hidden";
iframe.onload = function() {
iframe.style.position="initial";
iframe.style.visibility="initial";
};
});
</script>
Once the DOM has been parsed, I hide the iframe and I set it to position:fixed
. That way it would show at the top of the page. No additional CSS required for this. I don't use display: none
because although it prevents the scroll, then my iframe content doesn't load correctly in some browsers (Chrome) when I set it back to display:block;
.
At the exact moment the iframe has loaded it triggers its scroll, even before you set the scroll position back to the top, so you see the page scrolling down and then back up, so it's not a good solution either. In my case I just set it back to its initial position and visibility.
So with this code when the scroll to the iframe is triggered the iframe is invisible at the top of the page, and right after that it goes back to its original position, so no unwanted scroll is experienced.
Notice that this may mean that when you have scrolled down and you refresh the page, you will go back to the top instead of getting the refresh at the current scroll position.