Code Monkey home page Code Monkey logo

posthtml-lazyload's Introduction

posthtml-lazyload

NPM npm Deps DevDeps Build

It is possible to natively lazy load content through the loading="lazy" attribute on images and iframes, and it’s already possible on last 2 versions modern browsers except Safari. This plugin will do it for you!

Read more in Addy Osmani Blog.

⭐️ Star me on GitHub — it helps!

Before:

 <img 
   src="http://posthtml.github.io/posthtml/logo.svg" 
   alt="PostHTML" 
   width="220"
   heigth="200" 
   class="lazyload"
 > 

<iframe 
   src="video-player.html" 
   class="lazyload"
>
</iframe>

After:

 <img 
   src="http://posthtml.github.io/posthtml/logo.svg" 
   alt="PostHTML" 
   width="220"
   heigth="200" 
   class="lazyload"
   loading="lazy" <---
 > 

<iframe 
   src="video-player.html" 
   class="lazyload"
   loading="lazy" <---
>
</iframe>

Demo

DEMO

If you are using Chrome lower than 76 make sure you turn on both the Enable lazy frame loading and Enable lazy image loading flags.

CAN I USE

Install

npm i posthtml-lazyload --save-dev

Usage

Gulp

npm i gulp-posthtml posthtml-lazyload --save-dev
const gulp = require('gulp');
const postHTML = require('gulp-posthtml');
const postHTMLLazyLoad = require('posthtml-lazyload');

const config = () => ({
  plugins: [
    postHTMLLazyLoad({
      loading: 'eager',
      class: 'lazy',
    }),
  ],
});

gulp.task('posthtml', () => gulp.src('./build/*.html')
  .pipe(postHTML(config))
  .pipe(gulp.dest('./build')));

Webpack

npm i html-loader posthtml-loader posthtml-lazyload --save-dev
module: {
  rules: [
    {
      test: /\.html$/,
      use: [
        'html-loader',
        {
          loader: 'posthtml-loader',
          options: {
            plugins: [
              require('posthtml-lazyload')({
                 loading: 'eager',
                 class: 'lazy',
               })
            ]
          }
        }
      ]
    }
  ]
}

Options

Option Type description Possible subsets Default value
loading string Describes loading attribute. auto, eager, lazy lazy
class string Class of the elements to load lazily Any valid CSS class name lazyload

Contributing

See PostHTML Guidelines and contribution guide.

License MIT

posthtml-lazyload's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

posthtml-lazyload's Issues

feature_request(option): polyfill syntax

1. Summary

It would be nice, if posthtml-lazyload will be able to add polyfill syntax for images and iframes.

2. Reason of the desirability of introducing a new option

As of September 5, 2022:

  1. “Firefox only supports lazy loading for images”. “Safari supports lazy image loading. Lazy iframes loading can be enabled under the Experimental Features menu.”
  2. Safari supports lazy loading for iframes by default solely from version 15.4.

In September 2022 it still makes sense to use a polyfill. It would be nice if posthtml-lazyload will add its syntax automatically.

3. Example of desired behavior

It would be nice to have 2 different options for images and iframes. Because the time when the polyfill will no longer be needed for images and iframes may vary. For example, polyfill for images may not be relevant after a year, while polyfill for iframes, for example, after 3 years.

3.1. polyfill-img

If polyfill-img: true, img tag will be wrapped in <noscript class="loading-lazy"> like here:

<noscript class="loading-lazy"><img alt="Kira image description" src="path/to/kiraimage.webp" loading="lazy"></noscript>

3.2. polyfill-iframe

If polyfill-iframe: true, iframe tag will be wrapped in<noscript class="loading-lazy"> like here:

<noscript class="loading-lazy"><iframe title="Kira iframe title" src="https://path.to/kiraiframe" loading="lazy"></noscript>

Thanks.

feature_request(option): add attribute for all img and iframe

1. Предложение

Я думаю, было бы неплохо иметь опцию (например, add_for_all: true) добавления loading="lazy" всем элементам <img> и <iframe>.

2. Обоснование предложения

Я использую loading="lazy" для всех моих изображений и фреймов и не сталкивался со случаями, где я не должен этого делать.

При текущем поведении плагина, если не задано значение опции class, posthtml-lazyload добавляет loading="lazy" всем элементам <img> и <iframe>, у которых нет класса. Однако, если у изображения или фрейма уже есть класс, posthtml-lazyload не добавляет loading="lazy", и пользователям приходится добавлять loading="lazy" вручную всем <img> и <iframe>. Это отнимает время.

Хотелось бы, чтобы пользователи могли обходиться без этой ручной работы.

3. MCVE

3.1. KiraLazyLoading.html

<img src="https://64.media.tumblr.com/bb94d05f5881bcc4b8e100818135a86c/tumblr_o9hcmePILP1st5lhmo1_1280.jpg" alt="Kira first image">
<img src="https://64.media.tumblr.com/44dee314b41c7edcaab198d53c36cc37/tumblr_o9fp67ZnAK1st5lhmo1_1280.jpg" alt="Kira second image" class="KiraImgClass">
<iframe src="https://video.ploud.fr/videos/embed/1c93a77b-371d-446c-a293-6a872a2088a9" title="Kira first iframe"></iframe>
<iframe src="https://video.ploud.fr/videos/embed/8c9305e6-671e-4d4d-9abe-e045cc9740df" title="Kira second iframe" class="KiraIframeClass"></iframe>

3.2. Команда

npx posthtml KiraLazyLoading.html --use posthtml-lazyload --posthtml-lazyload.loading lazy

3.3. Поведение

3.3.1. Текущее
<img src="https://64.media.tumblr.com/bb94d05f5881bcc4b8e100818135a86c/tumblr_o9hcmePILP1st5lhmo1_1280.jpg" alt="Kira first image" loading="lazy">
<img src="https://64.media.tumblr.com/44dee314b41c7edcaab198d53c36cc37/tumblr_o9fp67ZnAK1st5lhmo1_1280.jpg" alt="Kira second image" class="KiraImgClass">
<iframe src="https://video.ploud.fr/videos/embed/1c93a77b-371d-446c-a293-6a872a2088a9" title="Kira first iframe" loading="lazy"></iframe>
<iframe src="https://video.ploud.fr/videos/embed/8c9305e6-671e-4d4d-9abe-e045cc9740df" title="Kira second iframe" class="KiraIframeClass"></iframe>

Плагин не добавил loading="lazy" изображению и фрейму, имеющим класс.

3.3.2. Желаемое

Вводим, например, такую команду:

- npx posthtml KiraLazyLoading.html --use posthtml-lazyload --posthtml-lazyload.loading lazy
+ npx posthtml KiraLazyLoading.html --use posthtml-lazyload --posthtml-lazyload.loading lazy --posthtml-lazyload.add_for_all true

И loading="lazy" добавляется всем изображениям и фреймам вне зависимости от класса или его отсутствия:

<img src="https://64.media.tumblr.com/bb94d05f5881bcc4b8e100818135a86c/tumblr_o9hcmePILP1st5lhmo1_1280.jpg" alt="Kira first image" loading="lazy">
- <img src="https://64.media.tumblr.com/44dee314b41c7edcaab198d53c36cc37/tumblr_o9fp67ZnAK1st5lhmo1_1280.jpg" alt="Kira second image" class="KiraImgClass">
+ <img src="https://64.media.tumblr.com/44dee314b41c7edcaab198d53c36cc37/tumblr_o9fp67ZnAK1st5lhmo1_1280.jpg" alt="Kira second image" class="KiraImgClass" loading="lazy">
<iframe src="https://video.ploud.fr/videos/embed/1c93a77b-371d-446c-a293-6a872a2088a9" title="Kira first iframe" loading="lazy"></iframe>
- <iframe src="https://video.ploud.fr/videos/embed/8c9305e6-671e-4d4d-9abe-e045cc9740df" title="Kira second iframe" class="KiraIframeClass"></iframe>
+ <iframe src="https://video.ploud.fr/videos/embed/8c9305e6-671e-4d4d-9abe-e045cc9740df" title="Kira second iframe" class="KiraIframeClass" loading="lazy"></iframe>

Спасибо.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.