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" []="image" />

The sample assumes blazy.js is included in your application bundle.

If you’re using Webpack, only two steps are required:

  1. Install blazy with NPM: npm install --save blazy
  2. In your Typescript custom typings definitions file, add the line declare module "blazy"
comments powered by Disqus