0

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

| improve this answer | |
  • 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? – Brandon Irwin Sep 4 at 17:26

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.