ng-image-preload
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

semantic-release CircleCI NPM Version

NG Image Preload

An image preload module for Angular using IntersectionObserver in favour of scroll listener's.

npm install --save @jaspero/ng-image-preloader

Setup

Import JpImagePreloaderModule in your @NgModule:

@NgModule({
    imports: [
        JpImagePreloaderModule.forRoot();
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule {}

Then in your component initialize the service:

class AppComponent implements OnInit {
  constructor(private preload: JpPreloadService) {}
 
  ngOnInit() {
    this.preload.initialize();
  }
}

The initialize method accepts an optional options object:

Options

Name Type Default
rootMargin string 0 50px
threshold number 0.1

A description for this options can be found here.

How To Use

There are two ways to consume the library. Using the service or the directive.

Service

Inject the PreloadService in to a component.

constructor(
    private _preloadPreloadService
) {}
 
// Then add an image element to the que like this:
addImage(elementHTMLElement, configElementConfig) {
    this._preload.addImage(element, config);
}

Directive

You can add the jpPreload directive to an img element like this:

<img src="initialImage.jpg" jpPreload="someImage.jpg"></img>

The initialImage.jpg will not be preloaded, this is usually a spinner or some other light image. The someImage.jpg image will be shown when the element is in view.

If you need to preload a background image the jpPreload directive can be placed on any html element like this:

<div class="some-element" jpPreload="someImage.jpg"></div>

To show an image initially you can add a css background-image to the class. This image will then be replaced when the element is in view.

You can also attach a fallback (loads if the requested image fails) like this:

<img
  src="initialImage.jpg"
  jpPreload="someImage.jpg"
  fallback="someFallback.jpg"
/>

Readme

Keywords

Package Sidebar

Install

npm i ng-image-preload

Homepage

jaspero.co

Weekly Downloads

4

Version

1.0.0

License

none

Unpacked Size

128 kB

Total Files

36

Last publish

Collaborators

  • flauc1