Angular 2: Lazy-loading images using bLazy.js
I recently had the need to integrate bLazy in an Angular 2 project. This is a pure Javascript library so the integration was straightforward but it does have a few drawbacks to be aware of, especially due to the way Angular renders elements.
The trick was wrapping bLazy initialization inside a setTimeout()
which seems to be the only way for bLazy to properly set itself up.
Here’s the code:
How to use it?
There’s an example in the directive documentation itself but here it is:
<div id="blazyContainer" [bLazyLoadImages]="images" [bLazyOffset]="300" style="overflow: scroll;">
<div *ngFor="let image of images">
<img class="b-lazy" src="placeholder.jpg" [attr.data-src]="image" />
</div>
</div>
The sample assumes blazy.js is included in your application bundle.
If you’re using Webpack, only two steps are required:
- Install blazy with NPM:
npm install --save blazy
- In your Typescript custom typings definitions file, add the line
declare module "blazy"