tjoskar / ng-lazyload-image

🖼 A small library for lazy loading images for Angular apps with zero dependencies

Home Page:https://naughty-bose-ec1cfc.netlify.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cancel pending requests if not visible any more

yacovg opened this issue · comments

Hi,
I have a page with a lot of thumbnails.
When user navigate to this page and leave before all images where loaded, then I want to cancel all the pending requests.
Is it possible to do it?

Yes, I have the same problem in some projects. I'll wait here

Hi, this is currently not possible but I think it should be. The problem is that we need a reference to the fetcher when the component unmount.

I will try to fix this in the next version.

This should be possible to do if you can fetch the image by fetch or similar mechanism. And it should be even simpler in the upcoming version 8.0.0-beta.2 (npm install ng-lazyload-image@8.0.0-beta.2). Please try it out and get back to me with what you think.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { LazyLoadImageModule, IntersectionObserverHooks, Attributes } from 'ng-lazyload-image';
import { AppComponent } from './app.component';

class LazyLoadImageHooks extends IntersectionObserverHooks {
  private http: HttpClient;

  constructor(http: HttpClient) { // You can inject what ever service you want here
    super();
    this.http = http;
  }

  loadImage({ imagePath }: Attributes) {
    return this.http.get(imagePath, {
      responseType: 'blob',
    }).pipe(map(blob => URL.createObjectURL(blob)));
  }
}

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpClientModule,
    LazyLoadImageModule.forRoot(LazyLoadImageHooks, [HttpClient])
  ],
  bootstrap: [AppComponent],
})
export class MyAppModule {}

Let me know if something is unclear or if it doesn't work for you. The plan is to leave the beta channel in a couple of days.

I have created a sandbox example here: https://codesandbox.io/s/lazy-load-image-with-httpclient-68785?file=/src/app/app.module.ts

The easiest way to test it is to:

  1. Load the page
  2. Open devtools, throttle the network
  3. Scroll down (fast) the page to trigger downloads
  4. Scroll up (fast) and switch page

Take a look at the downloads. The images should be canceled or at least stop being downloaded (I don't know why they don't always get marked as canceled but you should see that the download has been stoped).

Version 8.0.0 is now out.
Let me know if you have any issues or if it does not solve your issue.