Lazy loading with Angular

Why load it now when you can load it later?

Rūtenis Raila
Nov 10 · 5 min read

Intro

We’re going to build a simple application that fetches cards with images asynchronously into an Angular app from a Node.js Express server and only loads more after the user has scrolled to the bottom of the page.

End result

Prerequisites:

  • HTML, CSS, JavaScript
  • Familiarity with Angular or any other JavaScript framework
  • Basic understanding of HTTP requests
  • Basic knowledge of Node.js

What is lazy loading?

Lazy or on-demand loading is simply a way to load content into a website only after the user has requested to see it.

Chrome’s network tab when scrolling through the page

In the example above you can see that additional cards are only loaded only after the user starts scrolling.

Why use lazy loading?

By loading images and videos only when they’re needed we can dramatically speed up web apps. This will ultimately offer better user experience especially for users running the app on a mobile data plan.

Getting started

We’re going to start by making a folder in your project directory. Open your terminal and type:

mkdir server 

As you’ve probably guessed our express server will run in the server folder while our angular app will be built in the client folder which will be later generated by the CLI.

Working on the server

In your server folder run the following to create an empty package.json file:

 npm init -y

You’ll need Express for the server:

npm i express

And Nodemon for auto-reload after you make a change in your code:

npm i nodemon -D

Open package.json in your favourite code editor and add the following scripts:

"scripts": {
"start": "node server",
"dev": "nodemon server"
},

Create a new file called server.js and paste the following code in:

Our server code

Server.js serves items.js file on /api/items route which doesn’t exist yet, so let’s create it along with needed folders and mock data file.

Create the following directories and files:

/server
server.js
/data
items_list.js
/routes
/api
items.js

Grab some mock data for your items_list.js:

https://github.com/railaru/angular-lazy-load/blob/master/server/data/item_list.js

Create a simple API endpoint with pagination function in items.js:

Note: since our server is running locally, responses will be almost instant. To simulate a live server that will be a lot slower, a 1-second timeout is added before the endpoint is sending the response back.

Awesome! We can get our server up and running by typing the following inside /server folder:

npm run dev

Open the Postman app and make a test GET request to your endpoint from items.js.

Articles 3 and 4 are getting returned as we passed page/2 and amount/2 as parameters for the API endpoint.

Working on client

Now that we have our server running and serving some mock data for our app, we can start working on the front-facing part of the project using Angular.

Generating boilerplate

Make sure you have Angular CLI installed to generate the boilerplate code for the client:

ng new client

Choose SCSS as your style preprocessor.

We’ll need an Angular service and some components for our app, so let’s use the CLI to generate them while we’re at it.

Inside /client, generate a service that will talk to the back end API we made earlier:

ng g s api

And of course, the UI components that we’ll use for the layout and styling of the app:

ng g c grid && ng g c card && ng g c card-shimmer

Next, you’ll need to create an interface to type check your front end code. Create a file named item.interface.ts and add the following code:

The last 2 files we’ll need are for styling. Create _typograhpy.scss and _animations.scss.

_typography.scss
_animations.scss

After creating .scss files, make sure to import them to styles.scss.

Finally, we need to organize our front end app a bit. Organize the boilerplate you just generated into the following structure:

/client/src/app/
/components
/containers
/grid
/presentationals
/card
/card-shimmer
/services
api.service.ts
api.service.spec.ts
/interfaces
item.interface.ts
/style
_animations.scss
_typography.scss

Implementing front end functionality

Now that the boilerplate code for the Angular app is generated, we can start connecting it to the Express API that serves paginated items on:

http://localhost:5000/api/items/page/1/amount/12

Add the following code to api.service.ts:

fetchItems() method returns an observable with a type of ItemInterface[]. We’ll be able to subscribe to the values this method receives from the server.

paginatePage() simply increments page number for the API request URL so that each time it’s called, we could get new items from the server and show them to the user as the page is scrolled.

We now have data in our Angular app, but to show it to the user, we need to connect to the Angular API service and pass received values to the presentational components.

Add this code to the grid component:

Inside this component, we’ll check if the user has scrolled to the bottom of the page and if so, fetch more values from the API.

Note: make sure to add HttpClientModule to imports and ApiService to providers inside app.module.ts

Inside grid.component.html add the following layout:

Make a simple responsive grid using CSS grid:

Card component needs to receive values passed from the grid component, so let’s pass them via Angular “@Input” decorator:

card.component.html
card.component.scss

Cool! Let’s add some styling to the shimmer cards so we could see them instead of a blank screen before the content loads initially:

card-shimmer.component.html
card-shimmer.component.scss

Remove boilerplate from app.component.html and bring in the grid component wrapped inside a container:

Yaaay! Your new shiny (literally) lazy loading app is finished. Make sure you’re still running the server and run the following inside /client to start the Angular app:

ng serve -o
The end result should look like this

Thank you for reading and happy coding!


Resources & further reading:

JavaScript in Plain English

Learn the web's most important programming language.

Rūtenis Raila

Written by

Web Developer @luno

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade