0

I'm want to add a dynamic js remote file in my website. So far, I've added CSS file thanks to this, but I can't achieve to add CSS files.

I've an observer with that.

 <event name="controller_action_predispatch">
    <observer name="addCSS" instance="Portail\Axiane\Observer\AddCSS" shared="false" />
 </event>

My observer

   public function execute(Observer $observer)
    {
        $om = \Magento\Framework\App\ObjectManager::getInstance();
        /** @var \Magento\Framework\View\Page\Config $page */
        $page = $om->get('Magento\Framework\View\Page\Config');

        /** @var Http $request */
        $request = $observer->getRequest();
            $route_name = $request->getRouteName();
            if ($route_name == "test") {
                $remote = "http://...";
                $script_src = "$remote/static/freb.js";
                $properties = [
                    'attributes' =>
                        [
                            "att1" => "1",
                            "att2" => "2",
                        ]
                ];
                $page->addRemotePageAsset($script_src, "text/javascript", $properties);
            
        }
}

But the JS is added as a CSS, without the script/src but with a link/href in the head

0

Create a module with name M2Expert_Js by following below steps:

Step 1: Create registration.php under:

app/code/M2Expert/Js/registration.php

with content:

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'M2Expert_Js',
    __DIR__
);

Step 2: Create module.xml under:

app/code/M2Expert/Js/etc/module.xml

with content:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="M2Expert_Js" setup_version="0.0.1">
        <sequence>
            <module name="Magento_Backend"/>
             <module name="Magento_Sales"/>
            <module name="Magento_Quote"/>
            <module name="Magento_Checkout"/>
            <module name="Magento_Cms"/>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>

Step 4: Create events.xml under:

app/code/M2Expert/Js/etc/frontend/events.xml

with content:

<?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="layout_load_before">
        <observer name="m2expert_js_layout_render" instance="M2Expert\Js\Observer\LayoutRender" />
    </event>
</config>

Step 5: Create LayoutRender.php under:

app/code/M2Expert/Js/Observer/LayoutRender.php

with content:

<?php
namespace M2Expert\Js\Observer;

class LayoutRender implements \Magento\Framework\Event\ObserverInterface
{

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $action = $observer->getData('full_action_name');
        if($action == 'your_action_name')
            $observer->getLayout()->getUpdate()->addHandle('m2expert_dynamic_js');
        }

        return $observer;
    }
}

Step 5: Create LayoutRender.php under:

app/code/M2Expert/Js/view/frontend/layout/m2expert_dynamic_js.xml

with content:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <script src="http://example.com/abc.js" src_type="url"/>
    </head>
</page>

Flush the cache and run setup:upgrade, setup:di:compile and static:content:deploy.

Hope this helps!

0
+50

Follow Below Steps

Step-1 : Create routes.xml file at app/code/VendoreName/CustomLayout/etc/frontend and add below code.

<?xml version="1.0" ?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route frontName="customlayout" id="customlayout">
            <module name="VendoreName_CustomLayout"/>
        </route>
    </router>
</config>

Step-2 : Create Index.php file at app/code/VendoreName/CustomLayout/Controller/Index and add below code.

<?php

namespace VendoreName\CustomLayout\Controller\Index;

use Magento\Framework\App\Action\Action;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $resultPageFactory;
    protected $customerSession;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();
        return $resultPage;
    }
}

Step-3 : Create customlayout_index_index.xml file at app/code/VendoreName/CustomLayout/view/frontend/layout and add below code.

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="VendoreName_CustomLayout::css/my_custom_layout_css.css" />
        <script src="VendoreName_CustomLayout::js/my_custom_layout_js.js" />
    </head>
</page>

Here the file name must be like routename_controllername_actionname.xml and all characters must be in lowercase.

Add your css to app/code/VendoreName/CustomLayout/view/frontend/web/css/my_custom_layout_css.css

Add your Js to app/code/VendoreName/CustomLayout/view/frontend/web/js/my_custom_layout_js.js

Step-4 : Create events.xml file at app/code/VendoreName/CustomLayout/etc and add below code.

<?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="layout_load_before">
        <observer name="custom_layout_css_js_add" instance="VendoreName\CustomLayout\Observer\CustomLayoutHandler" />
    </event>
</config>

You can also use your event

we need to add to css and js before page layout that's why we use layout_load_before event.

Step-5 : Create CustomLayoutHandler.php file at app/code/VendoreName/CustomLayout/Observer and add below code.

<?php

namespace VendoreName\CustomLayout\Observer;

class CustomLayoutHandler implements \Magento\Framework\Event\ObserverInterface
{
    public function __construct(
        \Magento\Framework\View\Result\Page $pageResult,
        \Magento\Framework\View\LayoutFactory $layoutFactory
    ) {
        $this->_pageResult = $pageResult;
        $this->layoutFactory = $layoutFactory;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        // echo "string";exit();
        $layout = $this->layoutFactory->create();
        echo $blockFile = $layout->createBlock(\Magento\Framework\View\Element\Template::class)
            ->setTemplate("VendoreName_CustomLayout::customjs.phtml")->toHtml();
        // $layout = $observer->getData('layout');
        // $currentPageLayout = $this->_pageResult->getConfig()->getPageLayout();
        // if ($currentPageLayout == "customlayout") {
        //     $layout->getUpdate()->addHandle('customlayout_index_index');
        // }

    }
}

Add below code to your customjs.phtml file

<script src="<?php echo $block->getViewFileUrl('Vendorename_ModuleName::js/script.js').'?param=12';  ?>"></script>

Step-6 : Run mgento command

php bin/magento s:up
php bin/magento c:c
10
  • How can I add dynamic attributes to my script JS (step 3) ? Nov 30 '20 at 8:43
  • you can set attribute as into array and use with like stackoverflow.com/a/11149036
    – Msquare
    Nov 30 '20 at 8:47
  • create array of your attribute and access it into you js by using window.variableName
    – Msquare
    Nov 30 '20 at 8:48
  • I don't get it. What I need is to have something like this at the end : <script src="https://..." kr-public-key="..." kr-post-url-success="..."> </script> Nov 30 '20 at 8:57
  • you can add js file to using phtml also please check it updated answer and update me.
    – Msquare
    Nov 30 '20 at 9:26
0

I've ended up by adding this into my layout xml (which is kind of a mix of suggested answer)

<referenceBlock name="head.additional">
    <block class="Vendor\Module\Block\Scripts" name="frontuser_scripts" template="Magento_Theme::html/scripts.phtml"/>
</referenceBlock>

And simply getting params like this in my scripts.phtml

<?php

$client = $this->get_pz_client();
?>
<script
    src="<?php echo $client->getClientEndpoint();?>..scripts.min.js"
    public-key="<?php echo $client->getPublicKey();?>"
    post-url-success="paid.php">
</script>

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.