Lesson 1 of 8

Adding elements in one go

Goal

Change the page once instead of a thousand times

01

Explanation

Every call to append on an element that's in the page can force the browser to recalculate the layout, so adding a thousand elements in a loop can mean a thousand recalculations.

A DocumentFragment is a lightweight container that lives outside the page. You build everything inside it without that cost, then add it to the page once. When you do, the container itself disappears and only the elements inside it remain.

Setting innerHTML once is also a good option, but a fragment keeps your references to the elements you created and the event listeners attached to them. innerHTML builds the elements from a string, so you're left with none of that.

02

Your task

Write buildList(n) so it returns a DocumentFragment holding n items, then use it to add 500 items to the list in one go.

Checks

5 checks
  1. buildList is defined
  2. Returns a DocumentFragment, not an array or a string
  3. The fragment holds the requested number of items
  4. The fragment's items are li elements with text
  5. The list on the page has 500 items
03

Hints

0/3
Track lessons0 of 8 done

Find out where your page really loses time, and how to win it back by adding elements in one go, making fewer calls and never computing the same thing twice.

Advanced level, 8 lessons, 1.5 hours in total.

index.html
Preview
index.html100%
–/5

Press “Run and check” to grade your code.

5 checks listed under “Your task”.

Track lessons0 of 8 done

Find out where your page really loses time, and how to win it back by adding elements in one go, making fewer calls and never computing the same thing twice.

Advanced level, 8 lessons, 1.5 hours in total.