【问题标题】:jQuery $.get (async) big file blocks browserjQuery $.get (async) 大文件阻塞浏览器
【发布时间】:2010-08-14 08:27:34
【问题描述】:

我正在对 html 文件执行 jQuery $.get,在成功函数中,我过滤了一个选择块并将选项分开,将选择的文本呈现为 div 中的段落,并附加在我的标记中。 获取和呈现选择需要一段时间(大约有 8000 个),但我希望 div 一个一个显示并让我处理它们(我使用 .delegate 将单击和悬停事件分配给它们),但是它们一次全部显示出来,我的浏览器窗口被阻止了。 我什至在 $.get 之前使用 $.ajaxSetup 显式设置 async: true (这不是必需的,因为它是默认设置)。 我一定错过了一些基本的东西,但不知道是什么...... 提前感谢您的想法和提示。

【问题讨论】:

  • 你有 8000 个元素在一个选择中?
  • 我个人没有 8000 个元素/选项可供选择,我想让这个网站更漂亮、更实用(如果你愿意,可以在猪上涂口红)。我将 [最初] 也有大约 8000 个元素,但我想在它们上放置过滤和排序选项。我无法更改此网站的代码 - 如果可以的话,相信我会...

标签: jquery ajax browser get


【解决方案1】:

您应该以较小的块加载结果。在伪代码中会是这样的:

loadDataUsingAjax(url, index) {
  load the first index to index + 250 items async using an ajax call;
  if there are still more items
     a few mili seconds later call loadDataUsingAjax(url, index + 500);
}

loadDataUsingAjax(url, 0);

否则大多数浏览器,尤其是在速度较慢的计算机上,会在尝试更新 DOM 时冻结几秒钟。

更新:实际的 jQuery 代码

var CHUNK_SIZE = 500;
var DELAY = 100;

function loadDataUsingAjax(ajaxUrl, index) {
  $.ajax({
    url: ajaxUrl,
    data: {startIndex: index, chunkSize: CHUNK_SIZE},
    dataType: 'json',
    success: function(response) {
      // response is in JSON format
      // convert it into HTML and add it to the appropriate location in the page
      // response.hasMoreResults indicates whether there are more items in the result set
      if (response.hasMoreResults) {
         setTimeout(function() {
            loadDataUsingAjax(ajaxUrl, index + CHUNK_SIZE);
         }, DELAY);
      }
    } 
  });
}
loadDataUsingAjax("yourUrl", 0);

您的服务器端脚本应该执行以下操作:

startIndex = get the value of the startIndex request parameter;
chunkSize = get the value of the chunkSize request parameter;
// MySQL query
select ... from ... where ... limit startIndex, startIndex + chunkSize;
create a json result from the MySQL result set;
select count(...) from ... where ...;
if count(...) is > startIndex + chunkSize then set hasMoreElements = true

【讨论】:

  • 那么你的意思是不是 ajax 调用而是插入 8000 个元素导致浏览器停止运行?我有一台配备 2.8GHz Intel Core Duo 和 4Gig 内存的 MacBook Pro,所以我不一定会说这是一台速度慢的计算机。我认为异步 ajax 调用和 DOM 操作的整个想法是 not 阻塞浏览器窗口。我会尝试你的建议 - 关于如何将伪代码转换为 Javascript/jQuery 的任何想法?谢谢。
  • 是的,一次向页面添加大量 DOM 元素可以将其冻结几秒钟。异步调用仅防止浏览器在调用过程中冻结。实际的 DOM 插入不会异步执行。我会更新我的答案,把伪代码变成真正的 jQuery 代码。
  • > "你的服务器端脚本应该做这样的事情:" 问题出在 - 没有服务器端脚本,或者至少没有一个我可以影响或改变的脚本。我唯一的界面是讨厌的 html。我想我会吸进整个页面,然后分块插入 DOM。不过感谢您的提示!
  • "我想我会吸进整个页面然后分块插入 DOM。"我实际上是建议您这样做,因为在您的特定情况下,无论如何您都将显示所有 8000 个元素并一次获取所有元素,但将它们插入更小的块中,插入之间的延迟会更小更有意义。顺便说一句,在 StackOverflow 中,为有用的答案投票是件好事... :)
  • > “为有用的答案投票是件好事... :)” 我知道...我只是仍然缺少这样做的必要声誉点...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-14
  • 2011-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多