FilterImageLazyLoad.php

Same filename and directory in other branches
  1. 10 core/modules/filter/src/Plugin/Filter/FilterImageLazyLoad.php

Namespace

Drupal\filter\Plugin\Filter

File

core/modules/filter/src/Plugin/Filter/FilterImageLazyLoad.php

View source
<?php

declare (strict_types=1);
namespace Drupal\filter\Plugin\Filter;

use Drupal\Component\Utility\Html;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\filter\Attribute\Filter;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;
use Drupal\filter\Plugin\FilterInterface;

/**
 * Provides a filter to lazy load tracked images.
 */
final class FilterImageLazyLoad extends FilterBase {
    
    /**
     * {@inheritdoc}
     */
    public function process($text, $langcode) : FilterProcessResult {
        $result = new FilterProcessResult($text);
        // If there are no images, return early.
        if (stripos($text, '<img ') === FALSE && stripos($text, 'data-entity-type="file"') === FALSE) {
            return $result;
        }
        return $result->setProcessedText($this->transformImages($text));
    }
    
    /**
     * Transform markup of images to include loading="lazy".
     *
     * @param string $text
     *   The markup to transform.
     *
     * @return string
     *   The transformed text with loading attribute added.
     */
    private function transformImages(string $text) : string {
        $dom = Html::load($text);
        $xpath = new \DOMXPath($dom);
        // Only set loading="lazy" if no existing loading attribute is specified and
        // dimensions are specified.
        foreach ($xpath->query('//img[not(@loading="eager") and @width and @height]') as $element) {
            assert($element instanceof \DOMElement);
            $element->setAttribute('loading', 'lazy');
        }
        return Html::serialize($dom);
    }

}

Classes

Title Deprecated Summary
FilterImageLazyLoad Provides a filter to lazy load tracked images.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.