繁体   English   中英

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

[英]Drupal 7: how do I add the async attribute to an external JS script when using drupal_add_js?

我试过了:

  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'
  ]);

没有结果。

有谁知道我怎么能做到这一点?

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

建议使用defer ,它(恕我直言)更好,因为它不会阻止 HTML 解析

  • 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';
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM