Optimizing Angular: Leveraging ngx-bootstrap to dynamically load images for faster page loading

I am currently facing a challenge with loading a large number of images in a carousel on my webpage. The issue is that when the page loads, all 300 images are loaded at once, causing a significant delay. Instead, I would like the images to load dynamically as the user clicks on the "NEXT" or "PREV" button to improve the page's loading speed. Is this the right approach?

As a beginner in Angular, I am struggling to find the appropriate solution for this problem. I have looked into various resources but haven't found a clear answer that fits my needs.

Below is the code for the carousel where I display the images using NGX-BOOTSTRAP:

... (code example remains similar)

In the current implementation, only 6 images are shown at a time in the carousel, and the rest are loaded in advance causing unnecessary delays. To give you a visual representation, here is how it looks:

https://i.sstatic.net/zMj1a.jpg

And here is what I aim to avoid - loading all images at once before they are needed in the carousel:

https://i.sstatic.net/cEheb.png

If anyone could provide guidance on how to overcome this issue, I would greatly appreciate it. Thank you for your help in advance.

Answer №1

This question brings up an interesting concept. Initially, we will establish two arrays:

  • a masterArray containing all the URLs of images;
  • an imagesArray linked to the carousel, starting with only one image. This means that upon page load, only a single image is loaded.
  • We simply transfer a URL from the masterArray into the imagesArray during each slide change event (named activeSlideChange);

relevant HTML for a single slide carousel:

<carousel (activeSlideChange)='gotChange()'>
  <slide *ngFor="let img of imagesArray; let idx of index"  >
    <img src="{{img}}" alt="slide {{idx}}" style="display: block; width: 100%;">
  </slide>
</carousel>

relevant TS code for a single slide carousel:

import { Component, ViewChild } from '@angular/core';
import { CarouselComponent } from 'ngx-bootstrap';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild(CarouselComponent) myCarousel: CarouselComponent;
  name = 'Angular';
  masterArray = ['URLs of images here'];
  imagesArray = ['Initial image URL here'];
  loopcomplete: boolean = false;

  constructor() { }

  gotChange() {
    console.log('Slider changed', this.myCarousel.activeSlide);
    if (!this.loopcomplete) {
      if (this.myCarousel.activeSlide + 1 < this.masterArray.length) {
        this.imagesArray.push(this.masterArray[this.myCarousel.activeSlide + 1]);
      } else { this.loopcomplete = true; }
    }
  }

}

See the complete functioning stackblitz here

The following image demonstrates the lazy loading of images: https://i.sstatic.net/RQUTt.png

UPDATE: Considering the comment from the asker below... the relevant event is now identified as slideRangeChange

relevant HTML for a multi-slide carousel:

<carousel [itemsPerSlide]="itemsPerSlide"
          [singleSlideOffset]="singleSlideOffset"
          [noWrap]="noWrap"
          (activeSlideChange)='gotChange()'
          (slideRangeChange)='gotRangeChange()'
          [showIndicators]='false'
          [interval]='false'
           >
  <slide *ngFor="let img of imagesArray; let idx of index"  >
    <img [src]="img" alt="slide {{idx}}" style="display: block; width: 100%;">
  </slide>
</carousel>

relevant TS code for a multi-slide carousel:

import { Component, ViewChild } from '@angular/core';
import { CarouselComponent } from 'ngx-bootstrap';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild(CarouselComponent) myCarousel: CarouselComponent;
  name = 'Angular';
  masterArray = ['URLs of images here'];
  imagesArray = ['Initial image URLs here'];
  loopcomplete: boolean = false;
  itemsPerSlide = 2;
  singleSlideOffset = true;
  noWrap = true;
  activeRange = 0;

  constructor() { }

  gotRangeChange() {
    if (!this.loopcomplete) {
      if (this.activeRange + 2 < this.masterArray.length) {
        this.activeRange = this.activeRange + 2;
        this.imagesArray = this.imagesArray.concat(this.masterArray[this.activeRange]);
        this.imagesArray = this.imagesArray.concat(this.masterArray[this.activeRange + 1]);
      } else {
        this.loopcomplete = true;
      }
    }
  }
}

Check out the working stackblitz for the multi-slide carousel here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Working with intricately structured objects using TypeScript

Trying to utilize VS Code for assistance when typing an object with predefined types. An example of a dish object could be: { "id": "dish01", "title": "SALMON CRUNCH", "price": 120, ...

Adjust the standard size of the IMG tag using CSS

I have a simple image tag with an incorrect URL http://jsbin.com/monivava/1/edit <img src="http://placekitten!!!.com/g/200/200"> The issue is that the default size for this unsuccessful image is 18x20 (at least in Webkit), but I want it to be 0px ...

Attempting to locate an element within the DOM using TypeScript

I am completely new to TypeScript. I have been attempting to locate an element using a selector, but no matter what I tried, the findElement() method always returns undefined. Can someone please point out where my mistake might be? Any assistance would b ...

Error triggered by using double border property

I'm currently working on a simple form template and its corresponding style sheet, but I've encountered an issue. When using the "double" border property to style forms, it seems to push the border beyond the containing element, which is affectin ...

Discover all attributes annotated with @Input in Angular 4

My input component has a range of properties, with some being defined using the @Input decorator. Is there a way to determine during runtime which properties have been decorated with @Input? For example, given the following class: export class MyInputC ...

Guide for positioning buttons in front of an image using HTML and CSS

I need assistance placing buttons in specific positions above an image carousel using HTML and CSS code. Despite researching various resources, I am unable to resolve this issue. This is the HTML implementation: <!-- Image where buttons should be placed ...

Steps to access the Link URL when the class name transforms to display as block:

I'm currently working on a function that needs to trigger a click on a link only if a specific classname is set to display: block; Unfortunately, my coding skills are not advanced enough to accomplish this task. Here is what I have so far: https://j ...

An issue occurred while trying to use a function that has a return type of NextPage

After successfully implementing the code below: const HomePage: NextPage = () => ( <div> <div>HomePage</div> </div> ); I wanted to adhere to Airbnb's style guide, which required using a named function. This led me t ...

Is it possible to combine JavaScript objects using TypeScript?

Currently, I am dealing with two objects: First Object - A { key1 : 'key1', key2 : 'key2' } Second Object - B { key1 : 'override a' } I am looking to combine them to create the following result: The Merged Re ...

Is there a way to align a div to the center of the BODY element instead of its parent in

I have a sticky navigation bar with the tab "categories" that reveals the dropdown menu "categoriesDropdown" when hovered over. I want the dropdown menu to span the width of the screen and be centered on it. I also need the dropdown menu to stick to ...

Having trouble installing angular/cli on Windows7 64 bit using npm?

I am currently facing an issue while attempting to install angular-cli using the latest versions of npm (5.3.0) and node (v8.2.1) on a Windows7 64-bit environment. Both npm and node are functioning properly as expected. However, the installation process f ...

Tips on integrating Pagination in Angular Carbon Design System without relying on a TableModel

We are working with an array of objects (Paper) and utilizing a Search filter. Here is our code snippet in .html: <ibm-search placeholder="Search title" (clear)="clearSearch()" [(ngModel)]="listFilter" >Search</ibm-search> &l ...

What is the best way to add additional Typescript declarations to my NPM package before publishing it?

I am in the process of developing a Typescript package to be released on NPM. Along with the main declaration file produced by the Typescript compiler, I also want to include some custom declarations. However, when this package is installed as a dependency ...

Arrange the text below the button containers in a straight line

This is the current appearance of my page: Current This is what I'm aiming for: Expected Moreover, I want to ensure that when the screen is minimized and the width is reduced, the text remains neat and in the correct position. It should adapt and ...

Effective implementation of Ts.ED BullMQ during server initialization

Recently, I started using Tsed(newb) and wanted to incorporate the BullMQ plugin into my project. I needed to run a job immediately after the server starts, but I struggled with implementing it correctly. I referred to this helpful guide here and attempte ...

Interacting with Redis in an Angular application

Recently diving into Angular and the world of Redis, our application currently interacts with data from a Dot.net API. Would it be feasible to integrate Redis into our Angular application? ...

Issue encountered during ng2-redux installation

While attempting to use the https://www.npmjs.com/package/ng2-redux link, I encountered an issue when running npm install redux ng2-redux --save. Here is the stacktrace of the error: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\\Program Files& ...

Instructions for sketching a square at predetermined coordinates

Looking for a simple function to draw a box at specific coordinates x and y. I've searched for guides, but they all seem to provide excessive or insufficient information. Thanks in advance! ...

The process of sorting an array based on another array that has multiple elements

Currently dealing with two arrays: array1 containing elements [1, 2, 3, 4, 5] and array2 containing elements [3, 4]. My goal is to filter out elements in array1 that are also found in array2. The code I have written seems to work fine when array2 has only ...

Ways to determine the position of elements when they are centered using `margin:auto`

Is there a more efficient way to determine the position of an element that is centered using CSS margin:auto? Take a look at this fiddle: https://jsfiddle.net/vaxobasilidze/jhyfgusn/1/ If you click on the element with the red border, it should alert you ...