Reputation: 1041
I currently have a search box on my website that searches for images and returns the result as in a list element like so:
<ul>
<li rel="1"><img src="imgurl" /></li>
<li rel="2"><img src="imgurl" /></li>
<li rel="3"><img src="imgurl" /></li>
<li rel="4"><img src="imgurl" /></li>
</ul>
Then each image has a click event associated to it which just adds an overlay into the parent li of the image clicked.
Sometimes my search results will contain 300+ results, which on a desktop isn't much of a problem but on mobile devices it causes huge lag, e.g. when someone clicks on a image to add the overlay it can take 4-5 seconds before the overlay appears.
Now I thought of a way to fix this is the below:
Add all li elements into an array (AS A STRING NOT A DOM ELEMENT)
Destroy the original li elements.
Calculate the size of the screen and how many images can be shown at one time
Add a slider ui element to be used to scroll though the list
Based on the position of the slider and how many elements we can fit onto the screen extract from the array the elements we can actually see and destroy the rest
Loop though returned array results and add all results to a single string. Then append that string containing all the results we can see into the UL.
My question is will this actually give me a performance increase? As I belive my inital problem is just too many elements in the dom.
Also is this a common thing to do and or is there a better way to do it?
Thanks
Upvotes: 5
Views: 1147
Reputation: 336
The slow performance on mobile does seem to be due to the large number of items in the DOM. I've tried various ways to speed up the code on the jsfiddle (e.g. reducing the number of jQuery DOM requests) but it is still sluggish http://jsfiddle.net/5LfMt/15/
I've made a variation of the suggestion in your original question: http://www.strudel.org.uk/test/stack.html It is very rough and doesn't have any error checking but shows that the basic idea works and is quicker. It should probably also help with page render time as the browser doesn't have to render all 500 images initially.
I've assumed all your images have the same, known height. I created an array of file names and then determine which ones are visible. The top padding of the list gets updated to make sure we stay at the correct place in the document. I've attached a scroll listener which updates list - removes list items then adds the visible ones. One consequence of removing them from the DOM is that the overlay was removed too so I've created an array to record the status of the overlay.
Upvotes: 2