此页面上的脚本导致Internet Explorer运行缓慢

时间:2013-08-19 10:41:31

标签: jquery internet-explorer performance

我有jQuery代码:

...
var poleVstupu= {id:['31'],platny:['1'],datum:['2013-08-05 20:23:38'], ... };

for(var poleName in poleVstupu)
{
    $('[name='+poleName+']').val(poleVstupu[poleName]).change();
}
...
在Firefox中

这个代码工作正常,但在IE8中它会抛出...run slowly消息。如果我运行IE内置调试器,在...run slowly消息后它会抛出object doesn't support this property or method,但是如果我在$('[name='+poleName ...行设置断点,它就不会显示object doesn't ...消息。 / p>

如何更快地处理代码并阻止显示...run slowly消息?

2 个答案:

答案 0 :(得分:2)

我对此答案中的评论作出回应,因为它会更长并包含代码,但很可能不会成为答案。


浏览器很可能不会对name属性进行索引,因此每次都必须遍历文档中的每个元素才能找到匹配的名称。如果您将搜索限制在表单中,则可能会有更好的效果。例如:

var form = $("#form_id");

for(var poleName in poleVstupu)
{
    form.find('[name='+poleName+']').val(poleVstupu[poleName]).change();
}

(部分)非jQuery解决方案可以直接从DOM访问表单元素。例如:

var form = $("#form_id")[0]; // Get the DOM reference of the form

for(var poleName in poleVstupu)
{
    jQuery(form.elements[poleName]).val(poleVstupu[poleName]).change();
}

它也可以帮助您循环使用表单元素而不是对象。例如:

var form = $("#form_id")[0]; // Get the DOM reference of the form

for (var i = 0, len = form.elements.length; i < len; i++)
{
    var element = form.elements[i];
    if (typeof poleVstupu[element.name] !== "undefined")
      jQuery(element).val(poleVstupu[element.name]).change();
}

jQuery的性能随着每个版本的增加而增加。你不能使用1.10.x甚至2.x吗?


如果遗漏.change(),性能如何?


修改

非格式元素name无论如何都是无效的,所以你不应该使用它。我将使用id并在您需要执行此操作的所有元素上设置一个类:

$(".change-html").each(function() {
  if (typeof poleVstupu[this.id] !== "undefined") {
    $(this).html(poleVstupu[element.name]);
  }
});

或者如果你不能使用id,对于eaxmple,因为你有重复项,请使用data- attribute

<p data-change-html="your_name"></p>

$("[data-change-html]").each(function() {
  var element = $(this);
  var name = element.data("change-html");
  if (typeof poleVstupu[name] !== "undefined") {
    element.html(poleVstupu[name]);
  }
});

(但后者赢得了非常快的大多数人)。

答案 1 :(得分:0)

您是否在虚拟机中运行IE?如果是这样,请确保为虚拟机提供足够的RAM分配和CPU功率(如果可设置),以便脚本可以使用计算机的很大一部分功能运行。