提高jQuery函数的效率 [英] Improving Efficiency in jQuery function

查看:72
本文介绍了提高jQuery函数的效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此函数中的while语句在IE/firefox中运行太慢(阻止页面加载4-5秒),但在Safari中运行得很快...

The while statement in this function runs too slow (prevents page load for 4-5 seconds) in IE/firefox, but fast in safari...

它测量页面上文本的像素宽度,并截断直到文本达到理想宽度:

It's measuring pixel width of text on a page and truncating until text reaches ideal width:

function constrain(text, ideal_width){

    $('.temp_item').html(text);
    var item_width = $('span.temp_item').width();
    var ideal = parseInt(ideal_width);
    var smaller_text = text;
    var original = text.length;

    while (item_width > ideal) {
        smaller_text = smaller_text.substr(0, (smaller_text.length-1));
        $('.temp_item').html(smaller_text);
        item_width = $('span.temp_item').width();
    }

    var final_length = smaller_text.length;
    if (final_length != original) {
        return (smaller_text + '…');
    } else {
       return text;
    }
}

有什么方法可以改善效果?如何将其转换为冒泡排序功能?

Any way to improve performance? How would I convert this to a bubble-sort function?

谢谢!

推荐答案

将调用移至循环外的$(),并将其结果存储在一个临时变量中.除了调用.html()之外,运行该函数将是代码中最慢的事情.

move the calls to $() outside of the loop, and store its result in a temporary variable. Running that function is going to be the slowest thing in your code, aside from the call to .html().

他们非常努力地使库中的选择器引擎快速运行,但是与普通的javascript操作(例如在本地范围内查找变量)相比,它仍然慢一些,因为它必须与dom交互.特别是如果您使用的是这样的类选择器,则jquery必须遍历文档中的每个元素,从而查看每个类属性并在其上运行一个正则表达式.每次绕圈!尽可能从紧张的循环中获取尽可能多的东西. Webkit可以快速运行它,因为它具有.getElementsByClassName,而其他浏览器则没有. (还).

They work very very hard on making the selector engines in libraries fast, but it's still dog slow compared to normal javascript operations (like looking up a variable in the local scope) because it has to interact with the dom. Especially if you're using a class selector like that, jquery has to loop through basically every element in the document looking at each class attribute and running a regex on it. Every go round the loop! Get as much of that stuff out of your tight loops as you can. Webkit runs it fast because it has .getElementsByClassName while the other browsers don't. (yet).

这篇关于提高jQuery函数的效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆