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">
<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"></script>
<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 ?
Make sure to attach the
loadevent handler before it can possibly fire, like this:That being said, I’m not positive the
loadevent is required to fire if there was no actual load (your frame has nosrc), all browsers may be following the spec here, yet still be inconsistent. But…Safari has always been a little “off” withloadandreadyevents, so using the approach above will help that as much as possible. One last note,.appendTo()can take a selector directly 😉