Character Counter Super Slow - jQuery
I wrote this:
$('[name=item-title]').live('keyup',function(k){
char_limit=parseInt($('[data-charlimit]').attr('data-charlimit'));
total = char_limit-parseInt($(this).val().length);
$('.charcount span').text(char_limit-parseInt($(this).val().length));
});
But after the first few words it starts going super slow where I'll type and the words will show a millisecond after. If i get to like 250 words it gets nearly 3/4 of a second behind it 开发者_运维知识库seems. Any ideas why? To me what i wrote seems fairly minimal...
You're doing a DOM traversal per character and you're not sure why it's slow?
// calculate upper limit once -- it won't change, presumably
var char_limit=parseInt($('[data-charlimit]').attr('data-charlimit'));
$('[name=item-title]').live('keyup',function(k){
// length is already numeric, no need to parse it
var remaining = char_limit - $(this).val().length;
$('.charcount span').text( remaining ); // use the result, note I renamed it
});
- If possible, precalculate the
char_limit
. It won't change during the typing. - Use the
total
variable in your fourth line, or leave out its calculation completely - Leave out the
parseInt
s except for maybe the first one, they're useless.
This would give you
var char_limit=parseInt($('[data-charlimit]').attr('data-charlimit'));
$('[name=item-title]').live('keyup',function(k){
$('.charcount span').text(char_limit-$(this).val().length);
});
I'm not sure if there are multiple char_limit
s though, as this would ruin those. It seems that your current $('[data-charlimit]')
approach doesn't allow for those anyway.
精彩评论