Article thumbnail

Gulp LQIP small image placeholder generator plugin

I recently created a gulp plugin that generates HTML image placeholders using LQIP technique and allows to embed them in the background image, without any js or css code. It’s currently available on the npm repository.

Just an eye-catcher image (iStock)
Just an eye-catcher image (iStock)

LQIP stands for «Low-quality image placeholders» technique to provide already prepared small resource-effective image previews.

The plugin combines Johann Servoire’s gulp-image-lqip plugin and Nikita Dubko’s 11ty site solution to embed previews, but:

I used it in my TubeCaster Telegram Bot landing, get the real-life example there.

Basic usage

gulp.task('lqip', () =>
  gulp
    .src(['*.html'])
    .pipe(
      gulpEmbedLqipAsBackground({
        rootPath: __dirname,
        // lazyLoadClass: 'lazy-load',
        // srcAttr: 'src',
        // dataSrcAttr: '',
        // scaleFactorAttr: 'data-scale-factor',
        // scaleFactor: 10,
        // validFileExtensions: ['.html', '.htm'],
      }),
    )
    .pipe(gulp.dest('.')),
);

All the commented parameters are optional. See API reference

See the example: source code or demo html.

For example, the above command will process the images with lazy-load class, like this:

<img src="img/csb.jpg" class="img-fluid lazy-load figure" data-scale-factor="5" />

– to the code like this:

<img
  src="img/csb.jpg"
  class="img-fluid lazy-load figure"
  data-scale-factor="5"
  loading="lazy"
  style="background-size: cover; background-image: url(&quot;data:image/svg+xml;charset=utf-8,%3Csvg
    xmlns='http%3A//www.w3.org/2000/svg' xmlns%3Axlink='http%3A//www.w3.org/1999/xlink'
    viewBox='0 0 600 599'%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur
    stdDeviation='.5'%3E%3C/feGaussianBlur%3E%3CfeComponentTransfer%3E%3CfeFuncA type='discrete'
    tableValues='1 1'%3E%3C/feFuncA%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage
    filter='url(%23b)' preserveAspectRatio='none' height='100%25' width='100%25'
    xlink%3Ahref='data%3Aimage/jpeg;base64,/9j/---A LONG BASE64 ENCOED STRING IS COMING HERE---//2Q=='%3E%3C/image%3E%3C/svg%3E&quot;);"
  width="600"
  height="599"
/>

Notice the added loading="lazy" and width and height attributes, and the svg object with an embedded preview in the background css style.

Old (data-src, with js & css) approach

In case if you specify the dataSrcAttr options parameter (eg, with data-src), then it’ll behave in original way: by storing the downscaled preview in the specified attribute instead of style:background object.

But this approach required extra js code & styles, see those in the example: source code or demo html.

gulp.task('lqip', () =>
  gulp
    .src(['*.html'])
    .pipe(
      gulpEmbedLqipAsBackground({
        rootPath: __dirname,
        dataSrcAttr: 'data-src',
      }),
    )
    .pipe(gulp.dest('.')),
);

See also