Created
September 24, 2020 20:44
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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