1

I was trying to add an external JS, say https://foo.bar/script.js (the url is configurable via config data) via requirejs, and I was successful so far. But then I realized that I would need to provide a few data- attributes to the script for it to work properly. (I personally do not write or own the script, so I have no idea why it is designed like this.)

A working example looks like this:

<script src="https://foo.bar/script.js" data-foo="bar" data-john="doe" />

Here are what I have got so far:

Foo\Bar\view\frontend\layout\some_handle_here.xml

<body>
    <referenceContainer name="content">
        <block ifconfig="foo/bar/active" class="Foo\Bar\Block\Script" name="foobar-script" template="Foo_Bar::script.phtml" />
    </referenceContainer>
</body>

Foo\Bar\view\frontend\templates\script.phtml

<script>
   require.config({
       map: {
           '*': {
               'someCustomJs':  '<?php echo $block->getScriptUrl() ?>'
           }
       }
   });
</script>

Foo\Bar\Block\Script.php

class Script extends \Magento\Framework\View\Element\Template
{
    protected $scopeConfig;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        array $data = []
    ) {
        $this->scopeConfig = $scopeConfig;
        parent::__construct($context, $data);
    }

    public function getScriptUrl() {
        return $this->scopeConfig->getValue('foo/bar/script_url', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
    }
}

Foo\Bar\Block\view\frontend\web\js\script.js

define([
    'jquery',
    ...
    'someCustomJs'
],
function (
    $,
    ...
    customjs
) {
    'use strict';
    //...
    //...
    customjs.foobar()
    //...
    //...
});

The above script was successfully init-ed and the https://foo.bar/script.js was requested, when I accessed the page http://example.com/some/handle/here. But I have no clue how to add those data- attributes. Is it possible to achieve this by they way I tried or by requirejs? Or I would have to consider other methods like injecting the script tag directly to the HTML head?

Thanks for your attention and assistance in advance. Feel free to let me know if more details are needed.

Your Answer

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

Browse other questions tagged or ask your own question.