Skip to the code

Fix layout thrashing

The tea shop's menu shows its teas as cards in a grid, and the cards in a row should all be as tall as the tallest one. matchHeights(cards) does that. It groups the cards into rows by offsetTop (cards with the same offsetTop are in one row) and sets every card's style.height to its row's tallest offsetHeight, in pixels, as "240px". It returns the rows' heights, top row first. The cards start with no height set, so offsetHeight is the height each card's content needs.

The starter gets the heights right, but it measures and sizes one card at a time. From the second card on, every layout read comes right after a style write in the same task, so before it can answer, the browser has to lay the page out again: a forced synchronous layout, once per card. That pattern is layout thrashing. Rewrite matchHeights so every layout read comes before the first style write: measure every card, work out the rows, and then write each card's style.height once, and nothing else.

The tests watch the cards with trackLayout(), which logs every read and write and counts the forced layouts: with every read first, layout.forcedReflows() is 0 whatever the number of cards. The JavaScript question What are reflow and repaint, and what is layout thrashing? (reflow-repaint-layout-thrashing) explains the idea, and the main thread problem batch-reads-and-writes queues reads and writes for the next frame; this one fixes a function in place.

// First row: Green 180, Mint 240, Oolong 200. Second row: Black 150, White 190.
matchHeights(document.querySelectorAll(".card")); // [240, 190]
// Green, Mint, and Oolong are now 240px tall; Black and White are 190px.

What the tests check

  1. gives every card in a row the height of the row's tallest card
    const cards = Array.from(document.querySelectorAll(".card"));
    const layout = trackLayout(cards);
    [[0, 180], [0, 240], [0, 200], [260, 150], [260, 190]].forEach(([top, height], index) => layout.size(cards[index], { top, height }));
    expect(matchHeights(document.querySelectorAll(".card"))).toEqual([240, 190]);
    expect(cards.map((card) => card.style.height)).toEqual(["240px", "240px", "240px", "190px", "190px"]);
    
  2. reads every card before writing any style, so the browser never lays out early
    const cards = Array.from(document.querySelectorAll(".card"));
    const layout = trackLayout(cards);
    [[0, 180], [0, 240], [0, 200], [260, 150], [260, 190]].forEach(([top, height], index) => layout.size(cards[index], { top, height }));
    matchHeights(cards);
    expect(layout.log.includes("read")).toBe(true);
    expect(layout.log.lastIndexOf("read")).toBeLessThan(layout.log.indexOf("write"));
    expect(layout.forcedReflows()).toBe(0);
    
  3. writes each card's height once, and nothing else
    const cards = Array.from(document.querySelectorAll(".card"));
    const layout = trackLayout(cards);
    [[0, 180], [0, 240], [0, 200], [260, 150], [260, 190]].forEach(([top, height], index) => layout.size(cards[index], { top, height }));
    matchHeights(cards);
    expect(layout.log.filter((entry) => entry === "write")).toHaveLength(5);
    expect(cards.map((card) => card.getAttribute("style"))).toEqual(["height: 240px;", "height: 240px;", "height: 240px;", "height: 190px;", "height: 190px;"]);
    
  4. finds the rows by offsetTop, so a narrow screen's rows of two work too
    const cards = Array.from(document.querySelectorAll(".card"));
    const layout = trackLayout(cards);
    [[0, 200], [0, 170], [220, 160], [220, 210], [440, 180]].forEach(([top, height], index) => layout.size(cards[index], { top, height }));
    expect(matchHeights(cards)).toEqual([200, 210, 180]);
    expect(cards.map((card) => card.style.height)).toEqual(["200px", "200px", "210px", "210px", "180px"]);
    
  5. no forced layout however many cards there are
    const menu = document.getElementById("menu");
    const cards = Array.from({ length: 60 }, (_, index) => {
      const card = document.createElement("article");
      card.className = "card";
      card.textContent = "Tea " + index;
      menu.append(card);
      return card;
    });
    const layout = trackLayout(cards);
    cards.forEach((card, index) => layout.size(card, { top: Math.floor(index / 4) * 300, height: 100 + (index % 7) * 10 }));
    const heights = matchHeights(cards);
    expect(heights).toHaveLength(15);
    expect(heights[1]).toBe(160);
    expect(cards[5].style.height).toBe("160px");
    expect(layout.forcedReflows()).toBe(0);
    
  6. no cards: nothing is read or written
    const layout = trackLayout(Array.from(document.querySelectorAll(".card")));
    expect(matchHeights([])).toEqual([]);
    expect(layout.log).toEqual([]);
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).