开发者

optimize jquery loop to set widths

I'm trying to stop strings in a div expanding beyond the size of their variable-sized parent divs using the tactic of setting an overflow and fixing the width. I have about 4400 dom elements on the page (can't be decreased and typically can be more), but only about 100-300 need to be changed. Of course, not a problem in FF/Webkit which can do that in less than a second, but IE is extraordinarily slow at over 7 seconds.

I've already eliminated any dom traversing by using an array of pre-determined id elements to address the tags in question. Is there something I'm missing or some alternative trick to do this in a开发者_StackOverflow社区 shorter time for IE?

for (id in ids) {
    jq("#" + ids[id] + "_name").css({"overflow": "hidden",
        'width': jq("#" + ids[id]).innerWidth() - 1
    });
}


Well, at the point of being right down to the metal of the DOM and still not eliminating any speed, I've gone for the alternative which is to mitigate the problem so it's less of a problem for the user (maybe IE9 will save MS from this sort of embarrasment!). I looked at this blog entry by Nick Fitzgerald which showed a technique for overcoming the issue. So here, using Nick's pattern, is my solution in the end (just the part for handling IE, I left the non-IE version as is):

yieldingEach(ids, function(namebox) {
    var elemName = document.getElementById(namebox + '_name');
    if (elemName) {
        var elem = document.getElementById(namebox);
        elemName.style.width = (elem.scrollWidth - 4) + 'px';
    }
});


This is a non-jQuery version...verify it works in IE, but it would be slightly faster since you're not having jQuery do it for you.

for (id in ids) {
    var elemName = document.getElementById(ids[id] + '_name'),
        elem = document.getElementById(ids[id]);

    elemName.setAttribute('overflow', 'hidden');
    elemName.setAttribute('width', elem.innerWidth - 1);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜