Drupal 7:使用drupal_add_js时,如何将async属性添加到外部JS脚本中?

时间:2018-11-12 05:34:37

标签: javascript drupal drupal-7 drupal-hooks

我尝试过:

  drupal_add_js('http://somesite.com/pages/scripts/0080/8579.js', [
    'type' => 'external',
    'async' => TRUE
  ]);

  drupal_add_js('http://somesite.com/pages/scripts/0080/8579.js', [
    'type' => 'external',
    'async' => 'async'
  ]);

没有结果。

有什么我能做到吗?

1 个答案:

答案 0 :(得分:1)

您不能仅通过指定选项来实现此目的,因为drupal_add_js()不支持async属性。

建议使用 defer ,因为它不会阻止HTML解析,因此更好(imho)。

  • async:异步获取脚本,然后暂停HTML解析以执行该脚本,然后继续解析。

  • defer:脚本异步获取,仅在HTML解析完成后才执行。

但是,如果确实需要async属性,则可以实现hook_preprocess_html_tag来更改主题变量,如下所示:

function moduleortheme_preprocess_html_tag(&$variables) {
  $el = &$variables['element'];
  if ($el['#tag'] !== 'script' || empty($el['#attributes']['src'])) {
    return;
  }   

  # External scripts to load asynchronously
  $async = [
    'http://somesite.com/pages/scripts/0080/8579.js',
    #...
  ];

  if (in_array($el['#attributes']['src'], $async)) {
    $el['#attributes']['async'] = 'async';
  }
}