jQuery html() acting really slow
javascript, jquery, performance
Solution
25 tip to improve your jquery use
http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx
http://acsenthil.wordpress.com/2011/07/04/improve-your-jquery-25-excellent-tips/
- Load the framework from Google Code
- Use a cheat sheet
- Combine all your scripts and minify them
- Use Firebug’s excellent console logging facilities
- Keep selection operations to a minimum by caching
- Keep DOM manipulation to a minimum
- Wrap everything in a single element when doing any kind of DOM insertion
- Use IDs instead of classes wherever possible
- Give your selectors a context
- Use chaining properly
- Learn to use animate properly
- Learn about event delegation
- Use classes to store state
- Even better, use jQuery’s internal data() method to store state
- Write your own selectors
- Streamline your HTML and modify it once the page has loaded
- Lazy load content for speed and SEO benefits
- Use jQuery’s utility functions
- Use noconflict to rename the jquery object when using other frameworks
- How to tell when images have loaded
- Always use the latest version
- How to check if an element exists
- Add a JS class to your HTML attribute
- Return ‘false’ to prevent default behaviour
- Shorthand for the ready event
Problem
I was testing something I read earlier about how random `Math.random()` really is, and wanted to display 10000 numbers that was supposed to be a random number between 0 and 10000000. To see the test, I chose to just join the array of random numbers to a string with `<br>` between each integer. And then I just did `$("#"+elm).html(randomNumberString);` which was really slow. I just figured it was the generation and sorting of random numbers into an array. But as I started placing timers in my code, it got appearant that it was the output that was slowing everything down. Just as a test I did `document.getElementById(elm).innerHTML = randomNumberString;` jQuery.html(): 2500ms getElementById.innerHTML: 170ms I tried this across all 5 browsers, and the numbers were very close in all browsers... Am I using jQuery wrong in this instance? I also tried append and fetching the element before the timer started, so I could simply do `$(elm).html()`, but that didn't help. It seems to be the actual `html()` function that's slowing everything down..? EDIT I ended up doing this: ``` randomStringNumber = "<div>" + randomStringNumber + "</div>"; ``` and now the whole thing runs a lot faster: jQuery.html(): 120ms getElementById.innerHTML: 80ms Still faster using oldschool html, though. And if anyone has an answer to why wrapping it in one element is faster, I'd appreciate that...