Why is this jQuery plugin for adding commas in numbers lagging my webpage?
-
$.fn.digits = function(){ return this.each(function(){ $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); }) } Call it like this: $("#total").digits(); I think it lags because of me having a couple hundred of these: $("#total").digits(); Is there a way to get rid of that lag?
-
Answer:
Manipulations of the DOM, i.e. modifying the text of elements, moving elements, etc. is slow. Especially if you hundreds of them like you said. Also the fact that you are using replace, i.e. regex, means it has to match every single total. You could have as easy just to string manipulations which would have been more efficient.
Andrey Kulakevich at Quora Visit the source
Other answers
It would be much better to do that text manipulation on the server-side. Javascript should really only be used to perform tasks that cannot be accomplished server-side. That being said, I don't think your script is hugely problematic, unless it ran multiple times. I run it here (http://jsfiddle.net/A34Zx/) on 2000 numbers, and it only takes a split second. How often is your digits function being called?
Marty Naselli
Because you do massive DOM manipulation in your GUI thread. Will always cause lag. Why can't you just use number.toFixed()?
Thomas Symalla
function commaSeparateNumber(val){ while (/(\d+)(\d{3})/.test(val.toString())){ val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2'); } return val; } use it like this commaSeparateNumber("1234567") ;
Nikita Somaiya
Related Q & A:
- Why is this jquery callback for complete not executed?Best solution by Stack Overflow
- Which is the Best JQuery grid plugin?Best solution by Stack Overflow
- Why do eggs float by adding salt to water?Best solution by Yahoo! Answers
- How to stop a PC game from lagging?Best solution by wikihow.com
- Why are people posting numbers on facebook?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.