【问题标题】:Why does the browser hang when loading html from iframe into a parent of the iframe?为什么将 html 从 iframe 加载到 iframe 的父级时浏览器会挂起?
【发布时间】:2011-08-09 17:50:45
【问题描述】:

所以我已经“解决”了我的实际问题,并将问题改为询问“为什么这是个问题?”

我这里有这段代码:

<!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');
        });
      });
    });
  </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>

(应该可以通过将“test.html”更改为其他文件来测试它,只要它是本地文件即可;由于跨域限制,google.com 无法运行)

它完全按照我的意愿去做:首先它在#target 中创建一个不可见的 iframe,然后它更改表单以便它获取一个新的 URL 并以 iframe 为目标。提交时,iframe 会加载抓取的内容。加载时,iframe 中的 html 会替换 #target 中的 html。

问题是浏览器加载 iframe 后,它一直在加载……一些东西。 Firefox 没有说什么,并且愉快地不停地咕咕叫。 Safari 说出了点问题并停止了,我能从中得到的最好信息是 iframe 加载时发生了某种疯狂的递归。这并不理想。

当我将隐藏的 iframe 放在目标之外时,问题就消失了。仅当我确保在加载 html 后再次将 iframe 附加到目标时,它才会在 Firefox 中消失。

所以,我不再有实际问题,但我非常想知道为什么做我正在做的事情是一个问题:从隐藏的 iframe 加载 HTML 并使用它来替换 HTML 内容该 iframe 的父节点。

【问题讨论】:

  • 请指定浏览器+版本+操作系统。

标签: jquery html


【解决方案1】:

您可以在代码中添加一些消息,以准确找到它挂在哪一行。这应该会缩小故障范围。

【讨论】:

  • 我试过了,它没有挂在我能找到的任何地方。据我所知,基于此类警报,$iframe 的加载绑定仅在应该调用的时候调用一次。似乎我的代码在开始挂起时不再执行。
  • 我在一个添加了 google +1 按钮的网站上遇到了类似的问题,该按钮是一个 iFrame。我把它归结为网络速度导致它挂起,可能是这种情况吗?
  • 不可能因为文件在我的本地机器上。
猜你喜欢
  • 2013-07-20
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 2012-02-08
  • 2023-03-26
  • 1970-01-01
  • 2012-09-27
  • 1970-01-01
相关资源
最近更新 更多