Lazy Loading
Defer expensive operations to improve initial page load. Two approaches: init-based deferred loading and viewport-based lazy loading.
Init-based deferred loading
Component renders immediately with a placeholder, then fetches data after page load. Best for
above-the-fold content with expensive data. lace:init fires the method on mount, and lace:loading.init
shows the placeholder while it runs - no manual loading flag needed.
Loading balance...
Remaining Balance
class CreditBalance(Component):
balance: str = ""
def calculate_balance(self):
# Expensive query / external API call
self.balance = "$25.95"
def inline_template(self):
return """
<div class="...">
<div lace:loading.init>Loading balance...</div>
<div lace:loading.init.hidden>{{ balance }}</div>
<div lace:init="calculate_balance"></div>
</div>
"""
Viewport lazy loading
Component doesn't render until visible in viewport. Best for below-the-fold content that might not be needed.
class RecentActivity(Component):
activities: list = []
def mount(self):
# Expensive query - only runs when scrolled into view
self.activities = Activity.objects.select_related('user').all()[:50]
def inline_placeholder(self):
# one skeleton per incoming item, so the layout doesn't jump when it loads
return """
<div class="animate-pulse space-y-3">
<div class="h-16 bg-ink-200 rounded"></div>
<div class="h-16 bg-ink-200 rounded"></div>
<div class="h-16 bg-ink-200 rounded"></div>
</div>
"""
<!-- Component loads when scrolled into viewport -->
{% interlace 'RecentActivity' lazy=True %}
Declaring lazy on the component
Pass lazy=True at the tag, or make a component lazy by default by declaring lazy = True on the
class (handy for a component that is always heavy, so callers never have to remember the flag). A tag
lazy=False still overrides it for a single use.
class RecentActivity(Component):
lazy = True # lazy by default, wherever it's mounted
def mount(self):
self.events = Event.objects.recent() # runs only once visible
{% interlace "RecentActivity" %} {# lazy, from the class default #}
{% interlace "RecentActivity" lazy=False %} {# force eager for this one spot #}
Comparison
| Approach | When It Loads | Best For |
|---|---|---|
lace:init="method" |
Immediately after page render | Above-the-fold content, critical data with slow queries |
lazy=True |
When scrolled into viewport | Below-the-fold content, optional sections |