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?

2 Answers 2


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: [
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

  • 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, 2019 at 10:51
  • Hey @MatteoD how did you accomplish this? Sep 4, 2020 at 17:26

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');
    }, 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';


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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