Optimization
Script Loading​
Aspect | inline script | sync | async | defer | external + type="module" |
---|---|---|---|---|---|
Visualization | |||||
Present in Tag |
|
|
|
|
|
Loading Behavior | script is executed immediately when encountered | script is fetched immediately as the browser encounters the tag | script is fetched in parallel with HTML parsing | script is fetched in parallel with HTML parsing | fetched in parallel |
Execution Timing | immediate execution | script is executed immediately after it's downloaded, before continuing parsing the HTML document | script is executed as soon as it's downloaded, even if the HTML parsing is not finished | script is executed in order after HTML parsing is fully complete, just before DOMContentLoaded | deferred by default, executed after parsing |
Execution Order | based on document location | preserved, as per DOM order | not preserved - random order | preserved | preserved (per top-level await and import graph) |
Blocking Behavior | blocks HTML parsing | blocks HTML parsing | may block parsing at execution | does not block parsing | deferred behavior |
Notes | avoid for large code blocks; inline code can't use async or defer | default behavior; loading blocks rendering | non-deterministic execution order; may lead to race conditions | most preferred for non-blocking DOM-safe execution | always deferred by spec; uses strict mode automatically |
Use Cases | critical inline JS; not affected by async / defer | scripts that must run immediately, and manipulate DOM elements above them | analytics, tracking, or other scripts that don't depend on DOM or other scripts | scripts that depend on DOM elements, and must maintain execution order | modern ES Modules and top-level imports |
Optimization Strategies​
- Core
- JS
- CSS
- HTML
- Media
- Font
- Server-Side
- Advanced
Strategy | Description |
---|---|
Minimize HTTP Requests | Fewer files mean faster load times due to reduced browser requests |
Reduce File Sizes | Smaller assets (images, code, videos) download more quickly |
Optimize Critical Rendering Path (CRP) | Improve how fast key content appears and becomes usable |
Leverage Caching | Store files in-browser or via CDN to speed up repeat visits |
Prioritize User Experience | Make the site feel fast and responsive, even if not fully loaded |
Reduce Server Response Time (SSR) | Faster backend response improves overall frontend speed |
Strategy | Description |
---|---|
Minification | Minify code by removing unnecessary characters and shortening variable/function names |
Compression | Serve JS files with Gzip or Brotli compression enabled |
Code Splitting/Bundling | Bundle multiple JS files into a single file to reduce HTTP requests, and use code splitting to load smaller chunks on demand |
Lazy Loading (Dynamic Imports) | Load JS modules or components on demand, such as using import('./my-component.js') to load the component only when the promise resolves |
Tree Shaking (Dead Code Elimination) | Eliminate unused code from the final JS bundle to enable effective tree shaking |
Deferring Non-Critical JavaScript | Use async or defer attributes on <script> tags for non-essential JavaScript |
Optimize JavaScript Execution | Avoid long-running tasks on the main thread to maintain browser responsiveness by breaking up large tasks with setTimeout or requestAnimationFrame , using Web Workers for heavy computations, and applying debouncing or throttling for frequently fired events like scroll or resize |
Efficient DOM Manipulation | Minimize direct DOM manipulation, batch updates with documentFragment , use requestAnimationFrame for visual updates, and avoid layout thrashing by batching read/write operations to prevent forced synchronous reflows |
Remove Unnecessary Libraries/Dependencies | Audit your project for unused or bloated third-party libraries. Consider using lighter alternatives or writing custom code if feasible |
Strategy | Description |
---|---|
Minification | Remove unnecessary characters like whitespace, comments, and line breaks from CSS files |
Compression | Serve CSS files with Gzip or Brotli compression enabled on the server. This reduces the file size transferred over the network |
Critical CSS (Above-the-Fold CSS) | Extract the minimum CSS for "above-the-fold" content, inline it in the HTML <head> for faster rendering, and load the remaining CSS asynchronously |
Remove Unused CSS | Analyze your project to identify and remove CSS rules that are not used on any page. This drastically reduces file size |
Optimize Selectors and Rules | Use simpler selectors for faster matching, avoid unnecessary qualifications of IDs or classes, and limit @import rules to prevent blocking parallel downloads, favoring link tags instead |
Use CSS Sprites | Combine small background images into a single file and use CSS background-position to display segments, reducing the number of HTTP requests |
Srategy | Description |
---|---|
Remove Comments & Whitespace | Reduces file size by eliminating non-essential content |
Eliminate Redundant Tags | Keep HTML semantic and free of unnecessary elements |
Avoid Large Inline CSS/JS | Prevents bloated HTML and allows for better caching |
Validate HTML | Ensures consistent rendering and fewer browser issues |
Place CSS in head | Enables faster rendering and avoids unstyled content flashes |
Place JS at Bottom or Use async |
|
Use defer for Dependent Scripts | Loads scripts in order after HTML parsing, before |
Srategy | Description |
---|---|
Image Compression | Compress images to reduce file size without significant quality loss |
Choose the Right Image Format | Use JPEG for photographs, PNG for transparency or sharp-edged images like logos, SVG for resolution-independent vector graphics, and modern formats like WebP or AVIF for superior compression, with fallbacks for older browsers |
Responsive Images | Serve image sizes based on device, resolution, and viewport using srcset and sizes in <img> for automatic selection, and utilize the <picture> element for complex layouts or art direction |
Lazy Loading Images and Videos | Load media as it nears the viewport by using loading="lazy" on <img> and employ the Intersection Observer API for better control or support in older browsers |
Image Dimensions | Always specify width and height on <img> and <video> to prevent layout shifts and reserve space during loading |
Optimize Video Delivery | Compress videos and use modern formats like WebM and MP4 (H.264/H.265), stream instead of forcing full downloads, and preload metadata or small segments for faster playback start |
Strategy | Description |
---|---|
Reduce Font File Size | Subset fonts to include only necessary characters, use WOFF2 for modern, compressed formats with fallbacks like WOFF and TTF for older browsers, and load only required font weights and styles to remove unused styles |
Font Loading Strategy | Use the font-display property to control font loading and prevent "Flash of Invisible Text" FOIT, "Flash of Unstyled Text" FOUT, and "Flash of Faux Text" FOFT; additionally, preload critical fonts using <link rel="preload" as="font" crossorigin href="myfont.woff2"> in the <head> to fetch important fonts early |
Strategy | Description |
---|---|
Content Delivery Network (CDN) | Serve static assets like images, CSS, and JavaScript via a CDN to reduce latency by delivering content from the closest globally distributed server to the user |
Browser Caching (HTTP Caching Headers) | Configure headers like Cache-Control , Expires , ETag , and Last-Modified to instruct browsers on how long to cache static resources, reducing repeated downloads for returning visitors |
HTTP/2 or HTTP/3 | Ensure your server supports HTTP/2 or HTTP/3 for improved performance over HTTP/1.1, featuring multiplexing (multiple requests/responses over one connection), header compression (reducing request overhead), and server push (proactively sending likely-needed resources, though more limited in HTTP/3) |
Prefetching and Preloading (Resource Hints) | Use rel attributes in <link> tags to enhance perceived performance by utilizing preload to fetch critical resources early (e.g., fonts), prefetch for resources likely needed for future navigation, preconnect to open early connections to important third-party origins, and dns-prefetch to resolve DNS early for external domains |
Reduce Redirects | Minimize unnecessary redirects (e.g., HTTP to HTTPS, www to non-www) as each redirect adds an extra round-trip delay, slowing down page loading |
Server-Side Rendering (SSR) / Static Site Generation (SSG) | Improve Time To Interactive (TTI) by delivering HTML directly through Server-Side Rendering (SSR), where HTML is rendered on the server and sent fully formed to the browser, or Static Site Generation (SSG), where HTML files are generated at build time and served statically (e.g., via a CDN) for extremely fast load times |
Strategy | Description |
---|---|
WebAssembly (Wasm) | For highly computational tasks like video editing and gaming, WebAssembly enables near-native performance by allowing code compiled from languages such as C++, Rust, and Go to run in the browser |
Service Workers | Enable offline support by caching assets and API responses to serve cached content for fast repeat visits, and implement complex caching strategies like cache-first or network-first |
Performance Budgeting | Define limits on metrics such as JavaScript size, First Contentful Paint, and Time To Interactive (TTI), and enforce budgets through CI/CD to prevent performance regressions |
Continuous Performance Monitoring (RUM & Synthetic) | RUM (Real User Monitoring) captures real user performance data such as Core Web Vitals and load times, while Synthetic Monitoring simulates user sessions in test environments using tools like Lighthouse and WebPageTest in CI |
User-Centric Performance Metrics (Core Web Vitals) | Optimize for metrics that impact real user experience, including LCP (Largest Contentful Paint) for perceived load speed, CLS (Cumulative Layout Shift) for visual stability, and INP (Interaction to Next Paint) as a new responsiveness metric measuring full input-to-render delay |
Third-Party Script Optimization | Third-party scripts (e.g., analytics, chat, ads) can harm performance; therefore, audit to remove unnecessary scripts, use async or defer attributes, lazy load scripts only when needed (e.g., show chat on click), and host common libraries locally for better control |