Why does the browser hang when loading html from iframe into a parent of the iframe?
So I've "solved" my actual problem, and changed the question to ask "Why was this a problem?"
I've got this code here:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>iFrame Page Loading</title>
<script type='application/javascript' src='http://code.jquery.com/jquery-latest.js'></script>
<script type='application/javascript'>
$(document).ready(function() {
var $form = $('form');
var $target = $('#target');
// Create an invisible iframe right after the form.
var $iframe = $('<iframe name="_hidden"></iframe>').hide();
// Change this line to the commented version after it to fix all problems:
$target.append($iframe);
// $target.parent().append($iframe);
// Make the form target the iframe.
$form.attr('target', '_hidden');
// Make the form action the 'ajax_load' value.
$form.attr('action', $form.find('.ajax_load').attr('value'));
// On form submit, create an event to replace $target with iframe's
// contents on iframe load.
$form.submit(function() {
$iframe.bind('load', function() {
$target.html($iframe.contents().find('*').html());
// Uncommenting this line fixes Firefox but not Safari - see below
// $target.append($iframe);
$iframe.unbind('load');
});
})开发者_JS百科;
});
</script>
</head>
<body>
<form method='get' action=''>
<input type='hidden' class='ajax_load' value='test.html' />
<input type='submit' value='Load' />
</form>
<div id='target'></div>
</body>
</html>
(it should be possible to test this by changing "test.html" to something else as long as it's a local file; google.com wouldn't work because of cross-domain restrictions)
It does exactly what I want it to: first it creates an invisible iframe inside #target, then it changes the form so that it grabs a new URL and targets the iframe. On submit, the iframe loads the grabbed content. On load, the html in the iframe replaces the html in #target.
The problem is that after the browser loads the iframe, it keeps loading...something. Firefox doesn't say what and happily keeps chugging. Safari says something went wrong and stops, and the best information I can get out of it is that there's some kind of wild recursion happening with the iframe loading. This is not ideal.
The problem goes away when I put the hidden iframe outside of the target. It also goes away in Firefox only if I make sure the iframe is appended to the target again after loading the html.
So, I don't have a practical problem anymore, but I would very much like to know why exactly it's a problem to do what I was doing: loading HTML from a hidden iframe and using it to replace the HTML contents of that iframe's parent node.
You could put some messages in your code to find our exactly which line it's hanging on. That should narrow the fault down.
精彩评论