-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathDeferJS.php
More file actions
executable file
·62 lines (51 loc) · 1.9 KB
/
DeferJS.php
File metadata and controls
executable file
·62 lines (51 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
namespace React\React;
use Magento\Framework\App\Config\ScopeConfigInterface as Config;
use Magento\Framework\Event\ObserverInterface;
class DeferJS implements ObserverInterface
{
public function __construct(
protected Config $config
) {
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$removeAdobeJSJunk = boolval($this->config->getValue('react_vue_config/junk/remove'));
$response = $observer->getEvent()->getData('response');
if (!$response) {
return;
}
$html = $response->getBody();
if ($html == '') {
return;
}
if ($removeAdobeJSJunk) {
$response->setBody($html);
return;
}
// Check if defer JS is enabled (config or GET parameter)
$deferJS = $this->shouldDeferJS();
if ($deferJS) {
// Move scripts to bottom, but preserve scripts with no-defer attribute
$conditionalJsPattern = '@(?:<script type="text/javascript"|<script)(?![^>]*no-defer)(.*)</script>@msU';
preg_match_all($conditionalJsPattern, $html, $_matches);
$jsHtml = implode('', $_matches[0]);
$html = preg_replace($conditionalJsPattern, '', $html);
$html .= $jsHtml;
}
$response->setBody($html);
}
private function shouldDeferJS(): bool
{
// Check GET parameter first
if (isset($_GET['defer-js']) && $_GET['defer-js'] === "false") {
return false;
}
if (isset($_GET['defer-js']) && $_GET['defer-js'] === "true") {
return true;
}
// Fall back to config (default to true if not set)
$configValue = $this->config->getValue('react_vue_config/junk/defer_js');
return $configValue === null || $configValue === '' ? true : boolval($configValue);
}
}