Skip to content

Commit 0e4af05

Browse files
committed
optimize reflow from rough cards
1 parent debc8ae commit 0e4af05

1 file changed

Lines changed: 18 additions & 17 deletions

File tree

src/_scripts/rough-cards.js

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,8 @@
2424
// Insert canvas as first child
2525
card.insertBefore(canvas, card.firstChild);
2626

27-
// Function to draw the sketchy background
28-
function drawCard() {
29-
const rect = card.getBoundingClientRect();
30-
const width = card.offsetWidth;
31-
const height = card.offsetHeight;
32-
27+
// Function to draw the sketchy background with given dimensions
28+
function drawCard(width, height) {
3329
// Set canvas size
3430
canvas.width = width;
3531
canvas.height = height;
@@ -53,22 +49,27 @@
5349
});
5450
}
5551

56-
// Draw initially
57-
drawCard();
58-
59-
// Redraw on window resize
60-
let resizeTimeout;
61-
window.addEventListener('resize', () => {
62-
clearTimeout(resizeTimeout);
63-
resizeTimeout = setTimeout(drawCard, 100);
52+
// Use ResizeObserver for efficient resize handling (no forced reflow)
53+
const resizeObserver = new ResizeObserver(entries => {
54+
for (const entry of entries) {
55+
const { width, height } = entry.contentRect;
56+
if (width > 0 && height > 0) {
57+
drawCard(Math.round(width), Math.round(height));
58+
}
59+
}
6460
});
61+
resizeObserver.observe(card);
6562

6663
// Redraw when theme changes (theme is set on <html>)
67-
const observer = new MutationObserver(() => {
68-
drawCard();
64+
const themeObserver = new MutationObserver(() => {
65+
const width = card.offsetWidth;
66+
const height = card.offsetHeight;
67+
if (width > 0 && height > 0) {
68+
drawCard(width, height);
69+
}
6970
});
7071

71-
observer.observe(document.documentElement, {
72+
themeObserver.observe(document.documentElement, {
7273
attributes: true,
7374
attributeFilter: ['data-theme']
7475
});

0 commit comments

Comments
 (0)