I'm coding a chat application, and it's gotten a bit more complex, since I want it to have features such as delivery confirmation, message caching and so on.
Right now, the way I'm handling message caching is:
User clicks conversation
First batch of messages fetched from the server is stored in a "chunk", inside of an array.
- Each chunk is a document fragment with n number of messages (DOM elements) appended to it.
- When the user scrolls up, more chunks (fragments) are added to the array, as they are fetched from the server.
- When the user goes to another conversation, but then decides to load a previously loaded conversation, the script appends all fragments into a single one, and the big fragment is appended into the messages window.
This is how an array with message "chunks" would look like if the user has already fetched plenty of messages:
conversation[2].chunks = [
#document-fragment,
#document-fragment,
#document-fragment
];
Each fragment has about 10 messages appended inside.
Before using fragments, I was using strings, by getting the HTML representation of each message. Something like this:
conversation[2].chunks = [
'<span class="msg">Hey</span><span class="msg">Hey</span>...',
'<span class="msg">Bla</span><span class="msg">bla</span>...'
];
I decided to use fragments since I found manipulating each message easier (by doing stuff like fragment.getElementById), versus having to use innerHTML to parse the strings and manipulate the elements.
However, I'm now questioning whether it was the right choice, since I don't know if keeping fragments inside of an array is actually memory-intensive, or at least more memory-intensive than strings.
The other downside is that now, if I want to store the fragments in localStorage
, I'd have to convert each fragment's content to HTML strings, and when I want to use localStorage
along with my fragment system, I'd have to convert each HTML string back to document fragments.
Using fragments seemed more natural, but now I'm thinking of going back to keeping the HTML strings. It's a bit of work, though, since I don't have the old code anymore.
Is there any advantage of using fragments over HTML strings in this case?
Thank you.