Skip to content

Commit 004de49

Browse files
authored
Merge pull request #35 from magefan/9116-browser-lazy-load-by-default-and-add-all-blocks-to-lazyload
9116 browser lazy load by default and add all blocks to lazyload
2 parents 828b991 + 6bbcdd5 commit 004de49

File tree

13 files changed

+310
-31
lines changed

13 files changed

+310
-31
lines changed

Block/Adminhtml/System/Config/Form/DynamicRow.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@ class DynamicRow extends AbstractFieldArray
1919
*/
2020
protected function _prepareToRender()
2121
{
22-
$this->addColumn('block_identifier', ['label' => __('Block Identifier'), 'style' => 'width:170px']);
23-
$this->addColumn('first_images_to_skip', ['label' => __('First Images To Skip'), 'style' => 'width:170px']);
22+
$this->addColumn('block_identifier', ['label' => __('Block Identifier'), 'style' => 'width:350px']);
23+
$this->addColumn('first_images_to_skip', ['label' => __('First Images To Skip'), 'style' => 'width:70px']);
2424
$this->_addAfter = false;
2525
$this->_addButtonLabel = __('Add');
2626
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
/**
3+
* Copyright © Magefan ([email protected]). All rights reserved.
4+
* Please visit Magefan.com for license details (https://magefan.com/end-user-license-agreement).
5+
*
6+
* Glory to Ukraine! Glory to the heroes!
7+
*/
8+
9+
declare(strict_types=1);
10+
11+
namespace Magefan\LazyLoad\Block\Adminhtml\System\Config\Form;
12+
13+
14+
class Js extends \Magento\Config\Block\System\Config\Form\Field
15+
{
16+
public function _construct()
17+
{
18+
parent::_construct();
19+
$this->setTemplate('js.phtml');
20+
}
21+
22+
public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element)
23+
{
24+
return parent::render($element) . $this->toHtml();
25+
}
26+
}

Model/Config.php

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212

1313
use Magento\Framework\App\Helper\Context;
1414
use Magento\Framework\Serialize\SerializerInterface;
15+
use Magefan\LazyLoad\Model\Config\Source\Method;
16+
use Magefan\LazyLoad\Model\Config\Source\BlocksToLazyLoad;
1517

1618
/**
1719
* Lazy load config
@@ -23,7 +25,7 @@ class Config extends \Magento\Framework\App\Helper\AbstractHelper
2325
const XML_PATH_LAZY_BLOCKS = 'mflazyzoad/general/lazy_blocks';
2426
const XML_PATH_LAZY_METHOD = 'mflazyzoad/general/method';
2527
const XML_PATH_LAZY_NOSCRIPT = 'mflazyzoad/general/noscript';
26-
28+
const XML_PATH_LAZY_BLOCKS_TO_LAZY_LOAD = 'mflazyzoad/general/blocks_to_lazy_load';
2729

2830
/**
2931
* @var array
@@ -70,7 +72,15 @@ public function getConfig($path)
7072
*/
7173
public function getIsJavascriptLazyLoadMethod(): bool
7274
{
73-
return (0 === (int)$this->getConfig(self::XML_PATH_LAZY_METHOD));
75+
return (Method::JAVASCRIPT === (int)$this->getConfig(self::XML_PATH_LAZY_METHOD));
76+
}
77+
78+
/**
79+
* @return bool
80+
*/
81+
public function getIsAllBlocksAddedToLazy(): bool
82+
{
83+
return (BlocksToLazyLoad::ALL === (int)$this->getConfig(self::XML_PATH_LAZY_BLOCKS_TO_LAZY_LOAD));
7484
}
7585

7686
/**
@@ -112,7 +122,7 @@ public function getBlocksInfo(): array
112122
{
113123
if (null === $this->blocks) {
114124
$this->blocks = [];
115-
125+
116126
try {
117127
$blocks = $this->serializer->unserialize($this->getConfig(self::XML_PATH_LAZY_BLOCKS));
118128
} catch (\InvalidArgumentException $e) {
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php
2+
/**
3+
* Copyright © Magefan ([email protected]). All rights reserved.
4+
* Please visit Magefan.com for license details (https://magefan.com/end-user-license-agreement).
5+
*
6+
* Glory to Ukraine! Glory to the heroes!
7+
*/
8+
declare(strict_types=1);
9+
10+
namespace Magefan\LazyLoad\Model\Config\Source;
11+
12+
class BlocksToLazyLoad implements \Magento\Framework\Option\ArrayInterface
13+
{
14+
15+
const ALL = 0;
16+
const SELECTED = 1;
17+
18+
/**
19+
* @return array[]
20+
*/
21+
public function toOptionArray(): array
22+
{
23+
return [
24+
['value' => self::ALL, 'label' => __('All')],
25+
['value' => self::SELECTED, 'label' => __('Selected')],
26+
];
27+
}
28+
29+
/**
30+
* Get options in "key-value" format
31+
*
32+
* @return array
33+
*/
34+
public function toArray(): array
35+
{
36+
$array = [];
37+
foreach ($this->toOptionArray() as $item) {
38+
$array[$item['value']] = $item['label'];
39+
}
40+
return $array;
41+
}
42+
}

Model/Config/Source/Method.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ class Method implements \Magento\Framework\Option\ArrayInterface
3333
public function toOptionArray(): array
3434
{
3535
return [
36-
['value' => self::JAVASCRIPT, 'label' => __('Non-jQuery JavaScript Library')],
36+
['value' => self::JAVASCRIPT, 'label' => __('Non-jQuery JavaScript Library (Require Advanced Configuration)')],
3737
['value' => self::NATIVE, 'label' => __('Native Browser Lazy Loading')],
3838
];
3939
}

Plugin/BlockPlugin.php

Lines changed: 41 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -51,30 +51,37 @@ class BlockPlugin
5151
*/
5252
protected $labelsValues = [];
5353

54+
/**
55+
* @var array
56+
*/
57+
protected $skipBlocks = [];
58+
5459
/**
5560
* @param \Magento\Framework\App\RequestInterface $request
5661
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
5762
* @param Config $config
63+
* @param array $skipBlocks
5864
*/
5965
public function __construct(
6066
\Magento\Framework\App\RequestInterface $request,
6167
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
62-
Config $config
68+
Config $config,
69+
array $skipBlocks
6370
) {
6471
$this->request = $request;
6572
$this->scopeConfig = $scopeConfig;
6673
$this->config = $config;
74+
$this->skipBlocks = $skipBlocks;
6775
}
6876

69-
7077
/**
7178
* @param \Magento\Framework\View\Element\AbstractBlock $block
7279
* @param string $html
7380
* @return string
7481
*/
7582
public function afterToHtml(\Magento\Framework\View\Element\AbstractBlock $block, $html)
7683
{
77-
if (!$this->isEnabled($block, (string)$html)) {
84+
if (!$html || !$this->isEnabled($block, (string)$html)) {
7885
return $html;
7986
}
8087

@@ -100,9 +107,11 @@ public function afterToHtml(\Magento\Framework\View\Element\AbstractBlock $block
100107
</noscript>';
101108
}
102109

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

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

@@ -168,7 +177,13 @@ protected function removeFirstNImagesWithCustomLabel($html, int $numberOfReplace
168177
$count++;
169178
if ($count <= $numberOfReplacements) {
170179
$label = self::REPLACEMENT_LABEL . '_' . $count;
171-
$this->labelsValues[$label] = $match[0];
180+
$imgTag = $match[0];
181+
182+
if (strpos($imgTag, 'mfdislazy') === false) {
183+
$imgTag = str_replace('<img ', '<img mfdislazy="1" ', $imgTag);
184+
}
185+
186+
$this->labelsValues[$label] = $imgTag;
172187

173188
return $label;
174189
}
@@ -179,13 +194,15 @@ protected function removeFirstNImagesWithCustomLabel($html, int $numberOfReplace
179194

180195
/**
181196
* @param $html
182-
* @return array|string|string[]|null
197+
* @return array|mixed|string|string[]
183198
*/
184199
protected function revertFirstNImageToInital($html)
185200
{
186-
return preg_replace_callback('/' . self::REPLACEMENT_LABEL .'_\d+\b(.*?)/', function ($match) use (&$count) {
187-
return $this->labelsValues[$match[0]] ?? $match[0];
188-
}, $html);
201+
foreach ($this->labelsValues as $labelsValue => $img) {
202+
$html = str_replace($labelsValue, $img, $html);
203+
}
204+
205+
return $html;
189206
}
190207

191208
/**
@@ -209,6 +226,10 @@ protected function isEnabled($block, string $html): bool
209226
return false;
210227
}
211228

229+
if ($this->config->getIsAllBlocksAddedToLazy() && !$this->isBlockSkiped($block)) {
230+
return true;
231+
}
232+
212233
if (false !== strpos($html, self::LAZY_TAG)) {
213234
return true;
214235
}
@@ -219,4 +240,13 @@ protected function isEnabled($block, string $html): bool
219240

220241
return true;
221242
}
243+
244+
/**
245+
* @param $block
246+
* @return bool
247+
*/
248+
private function isBlockSkiped($block): bool
249+
{
250+
return in_array(get_class($block), $this->skipBlocks);
251+
}
222252
}
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
<?php
2+
/**
3+
* Copyright © Magefan ([email protected]). All rights reserved.
4+
* Please visit Magefan.com for license details (https://magefan.com/end-user-license-agreement).
5+
*
6+
* Glory to Ukraine! Glory to the heroes!
7+
*/
8+
9+
declare(strict_types = 1);
10+
11+
namespace Magefan\LazyLoad\Setup\Patch\Data;
12+
13+
use Magento\Framework\Setup\Patch\DataPatchInterface;
14+
use Magento\Framework\Setup\ModuleDataSetupInterface;
15+
use Magefan\LazyLoad\Model\Config as Config;
16+
use Magento\Framework\App\Config\Storage\WriterInterface;
17+
use Magento\Framework\App\Config\ScopeConfigInterface;
18+
use Magefan\LazyLoad\Model\Config\Source\Method as LazyLoadMethod;
19+
use Magefan\LazyLoad\Model\Config\Source\BlocksToLazyLoad;
20+
21+
class SaveDefaultLazyLoadMethod implements DataPatchInterface
22+
{
23+
/**
24+
* @var ModuleDataSetupInterface
25+
*/
26+
private $moduleDataSetup;
27+
28+
/**
29+
* @var Config
30+
*/
31+
private $config;
32+
33+
/**
34+
* @var WriterInterface
35+
*/
36+
private $configWriter;
37+
38+
/**
39+
* @param ModuleDataSetupInterface $moduleDataSetup
40+
* @param Config $config
41+
* @param WriterInterface $configWriter
42+
*/
43+
public function __construct(
44+
ModuleDataSetupInterface $moduleDataSetup,
45+
Config $config,
46+
WriterInterface $configWriter
47+
) {
48+
$this->moduleDataSetup = $moduleDataSetup;
49+
$this->config = $config;
50+
$this->configWriter = $configWriter;
51+
}
52+
53+
/**
54+
* Set Default Lazy Load Method as JS to keep existing lazy load config for customers that configured lazy laod.
55+
*
56+
* @return void
57+
*/
58+
public function apply()
59+
{
60+
$this->moduleDataSetup->startSetup();
61+
62+
$connection = $this->moduleDataSetup->getConnection();
63+
$tableName = $this->moduleDataSetup->getTable('core_config_data');
64+
65+
if ($this->config->getBlocksInfo()) {
66+
$query = $connection->select()
67+
->from($tableName, ['config_id', 'value'])
68+
->where('path = ?', Config::XML_PATH_LAZY_METHOD);
69+
70+
// if lazy load was installed previusly and lazy laod method not set yet, set js lazy load as a default method
71+
if (!$connection->fetchAll($query)) {
72+
$this->configWriter->save(Config::XML_PATH_LAZY_METHOD, LazyLoadMethod::JAVASCRIPT);
73+
$this->configWriter->save(Config::XML_PATH_LAZY_BLOCKS_TO_LAZY_LOAD, BlocksToLazyLoad::SELECTED);
74+
}
75+
}
76+
77+
$this->moduleDataSetup->endSetup();
78+
}
79+
80+
/**
81+
* @return array|string[]
82+
*/
83+
public static function getDependencies()
84+
{
85+
return [];
86+
}
87+
88+
/**
89+
* @return array|string[]
90+
*/
91+
public function getAliases()
92+
{
93+
return [];
94+
}
95+
}

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
"magefan/module-rocketjavascript": "Install Rocket JavaScript to optimize JS loading."
1010
},
1111
"type": "magento2-module",
12-
"version": "2.0.23.1",
12+
"version": "2.1.0",
1313
"authors": [
1414
{
1515
"name": "Magefan",

0 commit comments

Comments
 (0)