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 07, 2025
How to cache report queries with fixed timelines How to generate large reports asynchronously using job queues 1. 🧠 Report Query Caching wi...
Jul 31, 2025
The useCallback hook in React is used to return a memoized version of a callback function, so it's only recreated when its dependencies change. The...
Jan 27, 2026
Introduction React Native is one of the most widely used frameworks for cross-platform mobile application development. However, iOS build time ha...
Aug 09, 2025
Object-Oriented Programming (OOP) is a modern software development approach that divides an application into units called Objects that interact with...
Jul 13, 2025
Laravel provides multiple ways to write reusable query logic. The two most common approaches are using Scopes with Traits or the newer #[UseEloquentBu...
Aug 06, 2025
When building applications with React, there’s always a need to manage data that changes based on user interaction or from fetching external r...