I developed a small drupal module which bring the external Js to head tags.

  $scriptSrc = 'https://cdnjs.cloudflare.com/ajax/libs/jcarousel/0.3.5/jquery.jcarousel.min.js';
  $attachments['#attached']['html_head'][] = [
      $script = [
        '#type' => 'html_tag',
        '#tag' => 'script',
        '#attributes' => [
          'src' => $scriptSrc,
          'class'=>'abc',
          'defer'=>'TRUE'
        ]
      ]
    ];

but when i showed on frontend it shows https://prnt.sc/104psbq

<script src="https://cdnjs.cloudflare.com/ajax/libs/jcarousel/0.3.5/jquery.jcarousel.min.js" class="abc" defer="TRUE"></script>

it showing defer="true" or defer="defer" but must be like this defer or async only without double quotes and equal.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jcarousel/0.3.5/jquery.jcarousel.min.js" class="abc" defer ></script>

How can i make defer or async only in code

Comments

jaypan’s picture

You don't need to. The values being automatically added for the attributes are also valid.

Contact me to contract me for D7 -> D10/11 migrations.

wombatbuddy’s picture

It can be done if you attach the library instead of the script. The example:
my_module.libraries.yml 

my_library:
  version: 0.3.5
  js:
    https://cdnjs.cloudflare.com/ajax/libs/jcarousel/0.3.5/jquery.jcarousel.min.js: { type: external, minified: true, attributes: { defer: true } }

my_module.module 

/**
 * Implements hook_page_attachments().
 */
function my_module_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'my_module/my_library';
}

The screenshot of the result: https://ibb.co/84bWT0z

Reference: https://www.drupal.org/docs/theming-drupal/adding-stylesheets-css-and-ja...

ahaomar’s picture

i want to make it dynamic so from backend user can add or change the js. only issue is right now when i try to add defer it appears defer="defer" same with async.

SEO team belive that not good way only defer only appear in tag

thats why generate this post

jaypan’s picture

The SEO team is trying to talk as if they know what they are talking about, when they don't. There is no difference between the two.

Unfortunately however, you may not have any flexibility in this. I unfortunately don't have a solution on how to change it though.

Contact me to contract me for D7 -> D10/11 migrations.

ahaomar’s picture

Thanks! alot dear. i will implement @Jaypan

luigimannoni’s picture

This apparently does not work anymore in Drupal 9, all attributes are stripped out.

miiimooo’s picture

I just came across this. The correct way to do what you're trying to do is

$attachments['#attached']['html_head'][] = [
      $script = [
        '#type' => 'html_tag',
        '#tag' => 'script',
        '#attributes' => [
          'src' => $scriptSrc,
          'class'=>'abc',
          'defer'=> TRUE,
          'async' => TRUE,
        ]
      ]
    ];

Note that I changed the array values to boolean from string.