DEV Community

Cover image for DOM Updates Like a Pro
Sanjeev Sharma
Sanjeev Sharma

Posted on

DOM Updates Like a Pro

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

Alt Text

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)
  })
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode
  1. You create a new fragment using createDocumentFragment.
  2. Append your elements to the fragment.
  3. Finally, append the fragment to the actual DOM.

That's it! πŸ‘Œ

I hope you learned something and this helps you. πŸ™

Thank you for reading. πŸ‘‹

Connect with me on LinkedIn or Twitter. 🌏

Top comments (2)

Collapse
 
crabyke profile image
Duzmath Lajos

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!

Collapse
 
thesanjeevsharma profile image
Sanjeev Sharma

Wow! Gald, I could help you. πŸ™Œ