Javascript problem with iframe that's hidden before loaded

Aistina picture Aistina · Apr 28, 2010 · Viewed 18.9k times · Source

I have a page that contains an iframe that gets loaded using Javascript:

index.html

<iframe id="myFrame" width="800" height="600" style="display: none;"></iframe>
<div id="loader"><!-- some loading indicator --></div>

<script type="text/javascript">
function someFunction() {
  var myFrame = document.getElementById('myFrame');
  var loader = document.getElementById('loader');

  loader.style.display = 'block';

  myFrame.src = 'myFrame.html';
  myFrame.onload = function() {
    myFrame.style.display = 'block';
    loader.style.display = 'none';
  };
}
</script>

The page that gets loaded in the iframe contains some Javascript logic which calculates the sizes of certain elements for the purposes of adding a JS driven scrollbar (jScrollPane + jQuery Dimensions).

myFrame.html

<div id="scrollingElement" style="overflow: auto;">
  <div id="several"></div>
  <div id="child"></div>
  <div id="elements"></div>
</div>

<script type="text/javascript">
$(document).load(function() {
  $('#scrollingElement').jScrollPane();
});
</script>

This works in Chrome (and probably other Webkit browsers), but fails in Firefox and IE because at the time jScrollPane gets called, all the elements are still invisble and jQuery Dimensions is unable to determine any element's dimensions.

Is there a way to make sure my iframe is visible before $(document).ready(...) gets called? Other than using setTimeout to delay jScrollPane, which is something I definitely want to avoid.

Answer

Steven P. picture Steven P. · May 7, 2010

Some browsers assume that when "display:none" is applied to replaced elements (like Flash or an iframe) the visual info for that element is no longer needed. So, if the element is later displayed by the CSS, the browser will actually recreate the visual data form scratch.

I imagine that having the iframe default to "display:none;" makes the browser skip the rendering of the HTML so the tags don't have any dimensions. I would set the visibility to "hidden" or position it off the page rather than use "display:none;".

Good luck.