3 ms·
- Avoid an excessive DOM size: 1658 elements. That's insane.
by reallymental 6y ago
- Avoid an excessive DOM size: 1658 elements.
That's insane.
- azemetre 6y agoI can easily see how people fall into these traps. At my company we use styled-components for our styling library with react. Someone on the team made a few reusable components that styled the text correctly to what design wants (correct font, size, color, and all the typography goodies), you could even specify what element you wanted (p, span, h1-h6, etc) and it would base the styles of that for you. It was basically this: <Text type='paragraph' fontWeight='bold'>Some nicely styled letters</Text> After a few months of using these components are product got noticeably slower, and on certain pages it completely broke accessibility. After doing some digging, one (out of many) issues that hurt our performance was the needless HTML. Our link elements had nested span or p tags. Headings has span tags, buttons had span tags. Basically every interactive element had potentially 3-4 redundant tags. Our navigation bar, which has 4 links (no sub-navigation), was 100+ DOM nodes. Wildly inefficient. And this was a small section of the overall page, imagine something like a table displaying data with tabular elements. That alone can easily be 600-1500 elements. We didn't need to use a span tag to style text in a button element. We didn't need a paragraph tag to style text inside an anchor. But that's what we did. Our code basically looked like this: <CustomButton onClick={props.buttonChange}><Text type='span'>{props.text}</Text></Button> The above would be abstracted as another component and it would look innocuous as: <RefreshButton onClick={customEvent} text={refreshCopy} /> But this button would be comprised of so much DOM elements, you wouldn't have any idea unless you are constantly inspecting what everyone is doing (which is full time work itself, that some people don't want to do). How it hurt accessibility was that some screen readers (and potentially other assistive tech) can't parse large DOM trees, and the use case for these people simply wouldn't work (they couldn't traverse the page at all). This may be a limitation of how the device interacted with the accessibility tree and the DOM tree, but the failures are significant. Choosing certain tools can force you to go down a certain path and I'm still floored why we couldn't just use CSS and not rely on making multiple divs to customize certain components and just using css appropriately to style the text (rather than relying on text components). I'd estimate that we could probably get rid of 30-60% of some of our frontend code (styling and jsx) if we just used appropriate classes for our styles.