Skip to content

Commit

Permalink
Merge pull request #37 from magefan/improved-image-skipping-process
Browse files Browse the repository at this point in the history
refactoring
  • Loading branch information
magefan authored Sep 12, 2023
2 parents 26355f3 + d15a225 commit 577df63
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 80 deletions.
2 changes: 1 addition & 1 deletion Model/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public function getIsJavascriptLazyLoadMethod(): bool
/**
* @return bool
*/
public function getIsAllBlocksAddedToLazy(): bool
public function isAllBlocksAddedToLazy(): bool
{
return (BlocksToLazyLoad::ALL === (int)$this->getConfig(self::XML_PATH_LAZY_BLOCKS_TO_LAZY_LOAD));
}
Expand Down
157 changes: 78 additions & 79 deletions Plugin/BlockPlugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ class BlockPlugin

const REPLACEMENT_LABEL = 'mf-lazy';

const PATTERN = '#<img(?!\s+mfdislazy)([^>]*)(?:\ssrc="([^"]*)")([^>]*)\/?>#isU';

/**
* Request
* @var \Magento\Framework\App\RequestInterface
Expand All @@ -46,11 +48,6 @@ class BlockPlugin
*/
protected $config;

/**
* @var array
*/
protected $labelsValues = [];

/**
* @var array
*/
Expand Down Expand Up @@ -85,65 +82,75 @@ public function afterToHtml(\Magento\Framework\View\Element\AbstractBlock $block
return $html;
}

if ($this->config->getIsJavascriptLazyLoadMethod()) {
$numberOfReplacements = $this->config->getBlockFirstImagesToSkip($this->getBlockIdentifier($block));

$numberOfReplacements = $this->config->getBlockFirstImagesToSkip(
$this->getBlockIdentifier($block)
);
if ($numberOfReplacements) {
$html = $this->removeLoadingLazyAttributeFromFirstNImages($html, $numberOfReplacements);
}

if ($numberOfReplacements) {
$html = $this->removeFirstNImagesWithCustomLabel($html, $numberOfReplacements);
}
$html = $this->config->getIsJavascriptLazyLoadMethod()
? $this->prepareForJsLazyLoad($block, $html)
: $this->prepareForNativeBrowserLazyLoad($html);

$pixelSrc = ' src="' . $block->getViewFileUrl('Magefan_LazyLoad::images/pixel.jpg') . '"';
$tmpSrc = 'TMP_SRC';
return $html;
}

$html = str_replace($pixelSrc, $tmpSrc, $html);

$noscript = '';
if ($this->config->isNoScriptEnabled()) {
$noscript = '<noscript>
/**
* @param string $html
* @return string
*/
private function prepareForJsLazyLoad($block, string $html): string
{
$pixelSrc = ' src="' . $block->getViewFileUrl('Magefan_LazyLoad::images/pixel.jpg') . '"';
$tmpSrc = 'TMP_SRC';

$html = str_replace($pixelSrc, $tmpSrc, $html);

$noscript = '';
if ($this->config->isNoScriptEnabled()) {
$noscript = '<noscript>
<img src="$2" $1 $3 />
</noscript>';
}

$html = preg_replace(
'#<img(?!\s+mfdislazy)([^>]*)(?:\ssrc="([^"]*)")([^>]*)\/?>#isU',
'<img data-original="$2" $1 $3/>' . $noscript,
$html
);

$html = str_replace(' data-original=', $pixelSrc . ' data-original=', $html);

$html = str_replace($tmpSrc, $pixelSrc, $html);
$html = str_replace(self::LAZY_TAG, '', $html);

/* Disable Owl Slider LazyLoad */
$html = str_replace(
['"lazyLoad":true,', '&quot;lazyLoad&quot;:true,', 'owl-lazy'],
['"lazyLoad":false,', '&quot;lazyLoad&quot;:false,', ''],
$html
);

/* Fix for page builder bg images */
if (false !== strpos($html, 'background-image-')) {
$html = str_replace('.background-image-', '.tmpbgimg-', $html);
$html = str_replace('background-image-', 'mflazy-background-image mflazy-background-image-', $html);
$html = str_replace('.tmpbgimg-', '.background-image-', $html);
}
}

if ($numberOfReplacements) {
$html = $this->revertFirstNImageToInital($html);
}
} else {
$html = preg_replace('#<img(?!\s+mfdislazy)([^>]*)(?:\ssrc="([^"]*)")([^>]*)\/?>#isU', '<img ' .
' src="$2" $1 $3 loading="lazy" />
', $html);
$html = preg_replace(
self::PATTERN,
'<img data-original="$2" $1 $3/>' . $noscript,
$html
);

$html = str_replace(' data-original=', $pixelSrc . ' data-original=', $html);

$html = str_replace($tmpSrc, $pixelSrc, $html);
$html = str_replace(self::LAZY_TAG, '', $html);

/* Disable Owl Slider LazyLoad */
$html = str_replace(
['"lazyLoad":true,', '&quot;lazyLoad&quot;:true,', 'owl-lazy'],
['"lazyLoad":false,', '&quot;lazyLoad&quot;:false,', ''],
$html
);

/* Fix for page builder bg images */
if (false !== strpos($html, 'background-image-')) {
$html = str_replace('.background-image-', '.tmpbgimg-', $html);
$html = str_replace('background-image-', 'mflazy-background-image mflazy-background-image-', $html);
$html = str_replace('.tmpbgimg-', '.background-image-', $html);
}

return $html;
}

/**
* @param string $html
* @return string
*/
protected function prepareForNativeBrowserLazyLoad(string $html) :string
{
return preg_replace(self::PATTERN, '<img src="$2" $1 $3 loading="lazy" />', $html);
}

/**
* @param \Magento\Framework\View\Element\AbstractBlock $block
* @return string
Expand All @@ -166,40 +173,32 @@ protected function getBlockIdentifier(\Magento\Framework\View\Element\AbstractBl
}

/**
* @param $html
* @param string $html
* @param int $numberOfReplacements
* @return array|string|string[]|null
* @return string
*/
protected function removeFirstNImagesWithCustomLabel($html, int $numberOfReplacements)
protected function removeLoadingLazyAttributeFromFirstNImages(string $html, int $numberOfReplacements):string
{
$count = 0;
return preg_replace_callback('#<img([^>]*)(?:\ssrc="([^"]*)")([^>]*)\/?>#isU', function ($match) use (&$count, &$numberOfReplacements) {
$count++;
if ($count <= $numberOfReplacements) {
$label = self::REPLACEMENT_LABEL . '_' . $count;
$imgTag = $match[0];

if (strpos($imgTag, 'mfdislazy') === false) {
$imgTag = str_replace('<img ', '<img mfdislazy="1" ', $imgTag);
$position = 0;

if (preg_match_all(self::PATTERN, $html, $matches, PREG_OFFSET_CAPTURE) !== false) {
foreach ($matches[0] as $i => $match) {
if ($i > $numberOfReplacements - 1) {
break;
}

$this->labelsValues[$label] = $imgTag;
$offset = $match[1] + $position;
$htmlTag = $matches[0][$i][0];

return $label;
}

return $match[0];
}, $html, $numberOfReplacements);
}
$newHtmlTag = str_replace(
['loading="lazy"', '<img '],
['', '<img mfdislazy="1" '],
$htmlTag
);

/**
* @param $html
* @return array|mixed|string|string[]
*/
protected function revertFirstNImageToInital($html)
{
foreach ($this->labelsValues as $labelsValue => $img) {
$html = str_replace($labelsValue, $img, $html);
$html = substr_replace($html, $newHtmlTag, $offset, strlen($htmlTag));
$position = $position + (strlen($newHtmlTag) - strlen($htmlTag));
}
}

return $html;
Expand All @@ -226,7 +225,7 @@ protected function isEnabled($block, string $html): bool
return false;
}

if ($this->config->getIsAllBlocksAddedToLazy() && !$this->isBlockSkiped($block)) {
if ($this->config->isAllBlocksAddedToLazy() && !$this->isBlockSkiped($block)) {
return true;
}

Expand Down

0 comments on commit 577df63

Please sign in to comment.