Hi! This will be a small article but the performance impact on your app will be huge. I am assuming you are a Junior Dev like me who is still learning and discovering new things every now and then.
You're given a task to fetch some data over an API and add it to DOM. You have different ways of doing this but let's go with the most naive approach which most of you will pick.
Naive Approach
This will get the job done! Looks fine. Yeah? 👎
Actually, this is not an efficient way to do this. DOM operations are heavy and every change you make can have side-effects that require recalculating layout, styles, etc.
// 100 posts
posts.forEach(post => {
const li = document.createElement('li')
li.textContent = post.title
listing.appendChild(li)
})
Right now, if there are 100 posts, you're updating the DOM 100 times. There are two ways to optimize this.
Not So Navie Approach
const populateList = (posts) => {
const listing = document.querySelector('#listing')
let postsHTML = ''
posts.forEach(post => {
postsHTML += `<li>${ post.title }</li>`
})
listing.innerHTML = postsHTML
}
Well, that's one way of doing it but this not what this article is about. 😜
Pro Approach
According to my current knowledge.
Introducing DocumentFragment.
DocumentFragment
is an off-screen DOM that behaves like actual DOM but it saves us from expensive reflow(DOM calculations).
Let's re-write our code using DocumentFragment
.
const populateList = (posts) => {
const listing = document.querySelector('#listing')
const fragment = document.createDocumentFragment()
posts.forEach(post => {
const li = document.createElement('li')
li.textContent = post.title
fragment.appendChild(li)
})
listing.appendChild(fragment)
}
- You create a new
fragment
usingcreateDocumentFragment
. - Append your elements to the
fragment
. - Finally, append the
fragment
to the actual DOM.
That's it! 👌
I hope you learned something and this helps you. 🙏
Thank you for reading. 👋
Top comments (2)
What a coincidence, yesterday I was coding almost the same what you have written.
Thanks for the tip, I will definitely try this method and also check what this fragment does!
Have a nice one!
Wow! Gald, I could help you. 🙌