Skip to content

Instantly share code, notes, and snippets.

@chrisfree
Created September 24, 2020 20:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisfree/bf290563b726d12ed1a799b7e7747223 to your computer and use it in GitHub Desktop.
Save chrisfree/bf290563b726d12ed1a799b7e7747223 to your computer and use it in GitHub Desktop.
A simple Drupal input filter for ensuring hard-coded images include native lazy loading attributes.
<?php
namespace Drupal\chromatic_lazyload\Plugin\Filter;
use Drupal\Component\Utility\Html;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;
/**
* Filter for altering hard-coded images to support native browser lazy loading.
*
* @Filter(
* id = "filter_lazyload",
* title = @Translation("Chromatic LazyLoad Filter"),
* description = @Translation("Updates hard-coded image element markup to include native lazy load attributes."),
* type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE,
* )
*/
class FilterLazyLoad extends FilterBase {
/**
* {@inheritdoc}
*/
public function process($text, $langcode) {
$result = new FilterProcessResult($text);
if (stristr($text, 'img') !== FALSE) {
$dom = Html::load($text);
$xpath = new \DOMXPath($dom);
foreach ($xpath->query('//img') as $node) {
// Set the loading attribute.
$node->setAttribute('loading', 'lazy');
}
$result->setProcessedText(Html::serialize($dom));
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment