function FilterImageLazyLoad::transformImages

Same name and namespace in other branches
  1. 11.x core/modules/filter/src/Plugin/Filter/FilterImageLazyLoad.php \Drupal\filter\Plugin\Filter\FilterImageLazyLoad::transformImages()
  2. 10 core/modules/filter/src/Plugin/Filter/FilterImageLazyLoad.php \Drupal\filter\Plugin\Filter\FilterImageLazyLoad::transformImages()

Transform markup of images to include loading="lazy".

Parameters

string $text: The markup to transform.

Return value

string The transformed text with loading attribute added.

1 call to FilterImageLazyLoad::transformImages()
FilterImageLazyLoad::process in core/modules/filter/src/Plugin/Filter/FilterImageLazyLoad.php
Performs the filter processing.

File

core/modules/filter/src/Plugin/Filter/FilterImageLazyLoad.php, line 49

Class

FilterImageLazyLoad
Provides a filter to lazy load tracked images.

Namespace

Drupal\filter\Plugin\Filter

Code

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);
}

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