Performance & Loading
Script Loading: async vs defer
async: Downloads in parallel, executes immediately when ready (can interrupt parsing). Best for independent scripts (analytics).defer: Downloads in parallel, executes only after DOM parsing completes, in document order. Best for DOM-dependent scripts.
<script src="analytics.js" async></script>
<script src="app.js" defer></script>
Native Lazy Loading
Delay off-screen images with built-in browser support:
<img src="photo.jpg" loading="lazy" alt="Description" width="600" height="400">
Always set width and height to prevent layout shifts.
Lazy Loading with Intersection Observer
For more control (custom thresholds, root margin):
const images = document.querySelectorAll('img[data-src]');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.removeAttribute('data-src');
observer.unobserve(img);
}
});
});
images.forEach(img => observer.observe(img));
Progressive Loading Techniques
- Blur-up: Load tiny low-quality placeholder first, then full image with CSS transition
- Fade/zoom: Overlay two images with CSS transitions
- LQIP (Low Quality Image Placeholder): Base64 inline tiny image as placeholder
<div class="blur-up">
<img src="tiny-blur.jpg" class="placeholder" alt="">
<img src="full.jpg" class="main" onload="this.classList.add('loaded')">
</div>
.blur-up .placeholder { filter: blur(10px); transition: opacity 0.4s; }
.blur-up .main { position: absolute; inset: 0; opacity: 0; transition: opacity 0.4s; }
.blur-up .main.loaded { opacity: 1; }
Preloading Critical Assets
Download important resources early:
<link rel="preload" as="image" href="hero.jpg">
<link rel="preload" as="font" href="font.woff2" type="font/woff2" crossorigin>
<link rel="preload" as="script" href="critical.js">
Resource Hints Summary
| Hint | Purpose |
|---|---|
preload | Fetch critical resource for current page |
prefetch | Fetch resource likely needed for next navigation |
preconnect | Establish early connection to a third-party origin |
dns-prefetch | Resolve DNS for a third-party origin |