1. Script Loading
Using async
- Why: Allows JavaScript files to load simultaneously with HTML parsing, reducing overall loading times.
- How:
<script async src="script.js"></script>
Example:
<html>
<head>
<script async src="analytics.js"></script>
</head>
<body>
<h1>Page Content</h1>
</body>
</html>
- When: Ideal for scripts that do not rely on the DOM or other scripts and can execute independently.
Using defer
- Why: Ensures scripts are loaded concurrently but executed only after HTML parsing completes, preserving script execution order.
- How:
<script defer src="script.js"></script>
Example:
<html>
<head>
<script defer src="app.js"></script>
</head>
<body>
<h1>Page Content</h1>
</body>
</html>
- When: Best used for scripts dependent on a fully parsed DOM, such as analytics or interactive components.
2. Lazy Loading
loading="lazy"
- Why: Reduces initial load times by delaying image or iframe loading until close to entering the viewport.
- How:
<img src="image.jpg" loading="lazy">
Example:
<img src="offscreen-image.jpg" loading="lazy" alt="Lazy loaded image">
- When: Suitable for off-screen images or content that appears lower on the page.