Load JavaScript on Demand to Boost Site Performance
July 24, 2025π§ What is Dynamic Import?
Dynamic import allows you to load JavaScript modules at runtime—only when needed. This approach is fantastic for reducing initial load time, improving perceived performance, and saving the user's bandwidth.
π‘ Example: Load a Chart Module on Click
Let’s say you have a button that shows a chart. Why load the chart logic upfront if the user may never click it?
<button class="btn btn-outline-dark" id="loadChart">Load Chart</button>
<script>
document.getElementById("loadChart").addEventListener("click", async () => {
const module = await import("./charts.js");
const {{ showChart }} = module;
if (typeof showChart === "function") {
showChart(); // Renders the chart
} else {
console.error("showChart function not found in charts.js");
}
});
</script>
Important: Make sure charts.js exports the function:
// charts.js
export function showChart() {
alert("Chart loaded successfully!");
}
π¨ Example: Load Script on Form Submit
There’s no need to load your form-handling logic until a user actually submits a form:
<form id="contactForm">
<input type="text" name="name" placeholder="Your name" required />
<button type="submit">Send</button>
</form>
<script>
document.getElementById("contactForm").addEventListener("submit", async (e) => {
e.preventDefault();
const module = await import("./formHandler.js");
const {{ processForm }} = module;
if (typeof processForm === "function") {
processForm(new FormData(e.target));
} else {
console.error("processForm function not found in formHandler.js");
}
});
</script>
Make sure your module looks like this:
// formHandler.js
export function processForm(formData) {
const name = formData.get("name");
alert("Data received: " + name);
}
β‘ Why It Matters
- β±οΈ Faster initial page load
- π¦ Smaller JavaScript bundles
- π Better performance scores (e.g., Google Lighthouse, Core Web Vitals)
- π§© Easier code maintenance and splitting
Blog
Jul 01, 2025
Essential React Native UI & Interaction Components React Native provides a powerful set of built-in components for creating native mobile apps....
Jul 06, 2025
π ECMAScript 2025 – Detailed Feature Guide All new ECMAScript 2025 features with code examples and explanation of their importance for front...
Jul 28, 2025
π What’s New in React Native 0.80? The React Native 0.80 release marks a pivotal moment in mobile development. This update not only enhances...
Jun 30, 2025
π Building a Task Reminder App This guide shows how to set up a Laravel app using MongoDB to implement a task reminder system with authentication,...
Jul 01, 2025
π Laravel Queue & Job System We’re gonna walk you through Laravel queues from setup to deploying in production using Supervisor. Step 1...
Jul 07, 2025
Mastering Laravel 12 Conditional Validation Laravel 12's validation system is super powerful, and conditional validation makes your forms...