-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
JsFooterPlugin.php
65 lines (59 loc) · 1.74 KB
/
JsFooterPlugin.php
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
63
64
65
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Theme\Controller\Result;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Framework\App\Response\Http;
/**
* Plugin for putting all js to footer.
*/
class JsFooterPlugin
{
private const XML_PATH_DEV_MOVE_JS_TO_BOTTOM = 'dev/js/move_script_to_bottom';
/**
* @var ScopeConfigInterface
*/
private $scopeConfig;
/**
* @param ScopeConfigInterface $scopeConfig
*/
public function __construct(ScopeConfigInterface $scopeConfig)
{
$this->scopeConfig = $scopeConfig;
}
/**
* Put all javascript to footer before sending the response.
*
* @param Http $subject
* @return void
*/
public function beforeSendResponse(Http $subject)
{
$content = $subject->getContent();
$script = [];
if (strpos($content, '</body') !== false) {
if ($this->scopeConfig->isSetFlag(
self::XML_PATH_DEV_MOVE_JS_TO_BOTTOM,
ScopeInterface::SCOPE_STORE
)
) {
$pattern = '#<script[^>]*+(?<!text/x-magento-template.)>.*?</script>#is';
$content = preg_replace_callback(
$pattern,
function ($matchPart) use (&$script) {
$script[] = $matchPart[0];
return '';
},
$content
);
$subject->setContent(
str_replace('</body', implode("\n", $script) . "\n</body", $content)
);
}
}
}
}