In my previous articles I explained optimization patterns such as deboucing and throttling, in this article let’s do a deep dive into lazy loading , which defers the loading of resources until they are actually needed. This article will walk you through a simple example of implementing lazy loading in a TypeScript web application.
What is Lazy Loading?
Lazy loading is a design pattern commonly used to delay the initialization of objects until the point at which they are needed. In the context of web development, this often refers to loading resources like images, scripts, or modules only when they are required, rather than at the start of the application. This can significantly reduce initial load times and improve overall performance.
Project Overview
We will create a web page with a button. When the button is clicked, a module containing a heavy computation function will be loaded and executed. This example uses TypeScript and native ES modules to achieve lazy loading.
Setting Up the Project
- Project Structure
lazy-loading-example/ ├── dist/ │ ├── index.html │ ├── app.js │ └── lazyModule.js ├── src/ │ ├── index.html │ ├── app.ts │ └── lazyModule.ts ├── tsconfig.json └── package.json
- Initialize the Project
npm install typescript --save-dev npx tsc --init
- Configure TypeScript
Edit ‘tsconfig.json
‘to target ES6 and use ESNext modules:
{ "compilerOptions": { "target": "es5", "module": "esnext", "outDir": "./dist", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"] }
Writing the Code
- Create HTML File
Create ‘src/index.html
‘ with a button and script tag
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lazy Loading Example</title> </head> <body> <h1>Lazy Loading Example</h1> <button id="loadButton">Load Module</button> <script type="module" src="./app.js"></script> </body> </html>
- Create Lazy Module
Create ‘src/lazyModule.ts
‘ which contains a heavy task function:
export const performHeavyTask = () => { console.log('Performing a heavy task...'); // Simulate a heavy task for (let i = 0; i < 1e7; i++) {} console.log('Heavy task completed.'); };
- Create Main Application File
Create ‘src/app.ts
‘ to handle button click and load the module
const loadButton = document.getElementById('loadButton') as HTMLButtonElement; loadButton.addEventListener('click', async () => { const module = await import('./lazyModule.js'); module.performHeavyTask(); });
Compile and Run
- Compile the TypeScript files
npx tsc
- Serve the Application
Use a static file server to serve the files. Here’s a quick way to do it using ‘http-server
‘
npm install -g http-server http-server dist
- Open in Browser
Open your browser and navigate to http://localhost:8080
(or the port http-server
provides). Click the “Load Module” button to see the lazy loading in action. The performHeavyTask
function from lazyModule
will be dynamically imported and executed, demonstrating lazy loading.
Conclusion
Lazy loading is an effective way to optimize web application performance by loading resources only when they are needed. In this example, we’ve seen how to implement lazy loading in a TypeScript web application using native ES modules. This technique can be extended to other resources like images and scripts to further enhance your application’s performance.
By adopting lazy loading, you can ensure that your web applications are both efficient and responsive, providing a better experience for your users
For complete source – https://github.com/IndikaMaligaspe/advance-javascrips/tree/master/topics/performance-optimization