Performance: Layouts and content_for
MEDIUM IMPACT
This affects the server-side rendering speed and the size of the HTML sent to the browser, impacting initial page load time.
<!-- layout.html.erb -->
<html>
<head>
<title>My Site</title>
</head>
<body>
<%= yield %>
<%= yield :sidebar %>
</body>
</html>
<!-- page.html.erb -->
<h1>Welcome</h1>
<div>Content here</div>
<% content_for :sidebar do %>
<div>Sidebar content</div>
<% end %><!-- layout.html.erb -->
<html>
<head>
<title>My Site</title>
</head>
<body>
<%= yield %>
<%= yield :sidebar %>
</body>
</html>
<!-- page.html.erb -->
<h1>Welcome</h1>
<div>Content here</div>
<div>Sidebar content</div>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Using content_for to inject sidebar content | Minimal extra DOM nodes | No additional reflows | No extra paint cost | [OK] Good |
| Duplicating sidebar content in page templates | More DOM nodes due to duplication | Potential reflows if layout changes | Higher paint cost due to larger HTML | [X] Bad |