1

I would like to add a custom data-attribute to a javascript injected in the frontend area using a custom module. My custom javascript is inserted using

    var config = {
        map: {
            '*': {
                my_module: 'My_Module/js/my-script'
            }
        }
    };

My goal is to have this:

<script type="text/javascript" charset="utf-8" async="" data-requirecontext="_" data-foo = "bar" data-requiremodule="My_module/js/my_js" src="http://example.com/pub/static/version1559902439/frontend/Magento/luma/en_EN/My_module/js/my_js.js"></script>

where data-foo is my custom data-attribute. I made some research in RequireJS documentation without success. Any ideas?

0

You could use onNodeCreated (needs requirejs 2.1.19 or newer) :

var config = {
paths: {
    slick:  'js/slick',
},
attributes: {
    "slick": {
      crossorigin: "anonymous" // your attributes here
    }
},
deps: [
    "js/main" 
],
shim: {
    'slick': {
        deps: ['jquery']
    }
},
onNodeCreated: function(node, config, name, url){
if(config.attributes && config.attributes[name]){
    Object.keys(config.attributes[name]).forEach(attribute => {
        node.setAttribute(attribute, config.attributes[name][attribute]);
        });
    }
}};

Take from https://stackoverflow.com/questions/49197939/add-crossorigin-attribute-to-script-tag-with-require-js

2
  • Thank for your suggestion I achieved my goal but I have two problems 1) requirejs version. 2) config the attribute data from backend setting
    – MatteoD
    Jun 10 '19 at 10:51
  • Hey @MatteoD how did you accomplish this? Sep 4 '20 at 17:26
0

At the time of writing the latest rev of Magento (2.4-develop) has requirejs 2.1.11, and upgrading will probably break things.

An alternative solution I have used is to manually place a script tag on the page, something like this:

require([], function() {
    // Listen for the one trust library to load
    document.addEventListener('OneTrustLoaded', function() {
        // Dispatch custom event that the one trust library supports
        // once it has loaded
        var eOT = new Event('OneTrustGroupsUpdated');
        document.dispatchEvent(eOT);   
    }, false);

    // Load the one trust library by manually placing a script tag on the page
    // We do this because M2 has requirejs 2.1.11 and we'd need >= 2.1.19 in
    // order to achieve this directly via requirejs-config.js
    var script = document.createElement('script');
    script.src     = 'https://cdn.cookielaw.org/scripttemplates/otSDKStub.js';
    script.type    = 'text/javascript';
    script.charset = 'UTF-8';
    script.dataset.documentLanguage('true');
    script.dataset.domainScript('customer-specific-value...');

    document.body.appendChild(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.