0

I am using a free extension for defer javascript Magento 2 Defer Parsing of JavaScript, which is working fine.

But when I am adding Miscellaneous Scripts in magento admin from head section which is also showing in footer but I want this script in head tag.

So how can I exclude head Miscellaneous Scripts from deferred?

I am using magento 2.3.0

Below code is used in this extension:

etc/frontend/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_front_send_response_before">
        <observer name="meetanshi_deferjs" instance="Meetanshi\DeferJS\Model\Observer" shared="false" />
    </event>
</config>

Helper/Data.php

<?php

namespace Meetanshi\DeferJS\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\ScopeInterface;

class Data extends AbstractHelper
{
    public function __construct(Context $context)
    {
        $this->scopeConfig = $context->getScopeConfig();
        parent::__construct($context);
    }

    public function isEnabled()
    {
        $active = $this->scopeConfig->getValue('deferjs/general/active', ScopeInterface::SCOPE_STORE);
        if ($active) {
            return true;
        }
        return false;
    }
}

Model/Observer.php

<?php

namespace Meetanshi\DeferJS\Model;

use Magento\Framework\Event\ObserverInterface;
use Meetanshi\DeferJS\Helper\Data;


class Observer implements ObserverInterface
{
    protected $_helper;

    public function __construct(
        Data $helper
    )
    {
        $this->_helper = $helper;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        if (!$this->_helper->isEnabled())
            return;
        $response = $observer->getEvent()->getData('response');
        if (!$response)
            return;
        $html = $response->getBody();
        if ($html == '')
            return;
        $conditionalJsPattern = '@(?:<script type="text/javascript"|<script)(.*)</script>@msU';
        preg_match_all($conditionalJsPattern, $html, $_matches);
        $_js_if = implode('', $_matches[0]);
        $html = preg_replace($conditionalJsPattern, '', $html);
        $html .= $_js_if;
        $response->setBody($html);
    }
}
0

replace below code in Observer.php file

<?php

namespace Meetanshi\DeferJS\Model;

use Meetanshi\DeferJS\Helper\Data;

class Observer implements \Magento\Framework\Event\ObserverInterface
{
    private $helper;

    public function __construct(
        Data $helper
    )
    {

        $this->helper = $helper;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $request = $observer->getEvent()->getData('request');
        if (!$this->helper->isEnabled($request)) {
            return;
        }
        $response = $observer->getEvent()->getData('response');
        if (!$response) {
            return;
        }
        $html = $response->getBody();
        if ($html == '') {
            return;
        }

        $conditionalJsPattern = '@(?:<script type="text/javascript"|<script)(.*)</script>@msU';
        preg_match_all($conditionalJsPattern, $html, $_matches);

        foreach ($_matches[0] as $key => $jsCode) {
            if (strpos($jsCode, 'googletagmanager.com') !== false) {
                unset($_matches[0][$key]);
            } else {
                $html = str_replace($jsCode, "", $html);
            }
        }

        $_js_if = implode('', $_matches[0]);
        //$html = preg_replace($conditionalJsPattern, '', $html);
        $html .= $_js_if;

        $response->setBody($html);
    }
}

this code is exclude the googletagmanager code , if you need to exclude any other script code than you just need to change googletagmanager.com word

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.