2

I've spent quite some time on drupal_add_js and didn't manage to solve this. How can I load an external JavaScript script which will also have the defer attribute?

I want to use this type of syntax:

drupal_add_js('http://example.com/whatever.js', 'external');

But it only produces:

<script src="http://example.com/whatever.js"></script>

I want the end HTML to be:

<script defer="defer" src="http://example.com/whatever.js"></script>
4

Try the following syntax:

drupal_add_js('http://example.com/whatever.js', array('type' => 'external', 'defer' => 'defer'));
6

Just add a value in $options

$options = array(
  'type' => 'external',
  'defer' => TRUE,
);
drupal_add_js('http://example.com/whatever.js', $options);

From the documentation:

Parameters

$options: (optional) A string defining the type of JavaScript that is being added in the $data parameter ('file'/'setting'/'inline'/'external'), or an associative array. JavaScript settings should always pass the string 'setting' only. Other types can have the following elements in the array:

  • type: The type of JavaScript that is to be added to the page. Allowed values are 'file', 'inline', 'external' or 'setting'. Defaults to 'file'.

  • ...

  • defer: If set to TRUE, the defer attribute is set on the tag. Defaults to FALSE.

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.