views:

55

answers:

1

I have a weird problem and I find no answer on google... I dynamically create and fullfil an iframe with jquery on a page. It works fine withFF and IE, but not with Safari.

The iframe is created but empty (the message "greetings from the iframe !" is missing). Here is a piece of code to illustrate it :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr-fr" lang="fr-fr" >
 <head>
  <title>iframe</title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
  <script type="text/javascript">
   $(document).ready(function() {

    var jFrame = $('<iframe id="myiframe" name="myiframe">');
    jFrame.css({'height':'40px','width':'200px'}).appendTo($('#container'));

    $('#myiframe').load(function() {
     jFrame.contents().find("body").html('greetings from the iframe !');
    });

   });
  </script>
 </head>
 <body>
  <div id="container"></div>
 </body>
</html>

I really wonder why the iframe stays empty with Safari. It seems like if "contents()" was not well interpreted...

Any idea ?

+2  A: 

Make sure to attach the load event handler before it can possibly fire, like this:

$('<iframe id="myiframe" name="myiframe" />')
  .css({'height':'40px','width':'200px'})
  .load(function() {
     $(this).contents().find("body").html('greetings from the iframe !');
  })
  .appendTo('#container');

That being said, I'm not positive the load event is required to fire if there was no actual load (your frame has no src), all browsers may be following the spec here, yet still be inconsistent. But...Safari has always been a little "off" with load and ready events, so using the approach above will help that as much as possible. One last note, .appendTo() can take a selector directly ;)

Nick Craver
Dear Nick,Thank you for your answer, it works fine !I'm quite newbie with jQuery and I honnestly don't understand why my piece of code does not work like yours. Is it something about synchro/asynchro ?Thank you once again,mhammout
@mhammout - The issue is that the `load` event fires *immediately* when you inserted it into the DOM, before your `.load(...)` even had a chance to run, so even though it rigged up a handler to run when that event happens, the event *already* happened, make sense?
Nick Craver
it does, thank you !
@mhammout - Welcome :)
Nick Craver