This One jQuery Mistake Froze Our Web Page! Here's the Fix You Need to Know
Niaz Bin Siraj

Niaz Bin Siraj @niazbinsiraj

About: Software Engineer at Therap(BD) Ltd. Tech Stack: JAVA | SPRING | HIBERNATE | MYBATIS | REACT | ORACLE | SQL

Location:
Dhaka, Bangladesh
Joined:
Oct 19, 2022

This One jQuery Mistake Froze Our Web Page! Here's the Fix You Need to Know

Publish Date: Apr 21
1 0

It was a normal morning at the office. We were working on a feature that shows a list of items on a web page using jQuery. Everything looked fine — until one of my teammates Adyel Ullahil Mamun noticed the page was acting weird.

Whenever the number of items increased, the browser became slow, sometimes even unresponsive. At first, we thought it was a server issue or maybe too much data. But no — the problem was hiding inside a small line of jQuery.

Let me show you.

items.forEach(item => {
  $('<li></li>').text(item.name).appendTo('#item-list');
});
Enter fullscreen mode Exit fullscreen mode

Looks simple, right? It just adds each item to a list. But here’s the hidden danger…

The Problem with .appendTo() in a Loop

When you use .appendTo() inside a loop, jQuery updates the DOM again and again, for each item. That means:

  • Your browser does a lot of extra work.
  • On large data, this becomes super slow.
  • The page can freeze or crash.

That’s exactly what was happening to us.

The Smart Fix: Use DocumentFragment

My teammate, sharp-eyed and smart, suggested a better way.

Instead of adding each item to the page one by one, we should first build everything in memory using a DocumentFragment— and then add it once to the page.

Here's the refactored version:

const fragment = $(document.createDocumentFragment());

items.forEach(item => {
  $('<li></li>').text(item.name).appendTo(fragment);
});

$('#item-list').append(fragment);
Enter fullscreen mode Exit fullscreen mode

And just like that — the page was smooth again!
Why? Because—

  • DocumentFragmentlets you build your elements in memory, not directly on the page.
  • You avoid many DOM updates — only one final update happens.
  • Your page becomes faster, even with large data.

If you are using .appendTo() inside a loop, stop and think:

Can I build everything first and append once?

This small change can save your users from frustration and keep your page lightning fast.

It’s amazing how a small mistake in a few lines of code can have a big impact. Thanks to my teammate’s sharp eye.

So next time your page starts lagging, check your loops — .appendTo() might be the silent troublemaker!

Liked this story?
Follow me for more real-world tips and coding lessons!

Comments 0 total

    Add comment