javascript - 德鲁帕尔 7 : how do I add the async attribute to an external JS script when using drupal_add_js?

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

没有结果。

有人知道我怎样才能做到这一点吗?

最佳答案

您不能仅通过指定选项来实现此目的,因为 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';
  }
}

关于javascript - 德鲁帕尔 7 : how do I add the async attribute to an external JS script when using drupal_add_js?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53256412/

相关文章:

php - 如何在 Drupal 7 中为节点设置自定义字段值?

drupal - 辉煌画廊 : where to put [bg|. ..] 标签?

git - 使用 git : committed changes in one branch affect 'master'

drupal - 如何制作仅在 Drupal 7 中首页使用的 node.tpl.php 文件

javascript - 使用 AngularJS 和 ng-if 检查用户是否存在

javascript - 在 Google Chrome 扩展程序中使用 SSH

drupal - 如何在 Drupal 7 中创建标签云?

php - 德鲁帕尔 7 : Localhost/user link defaults to website/user

javascript - 我在 jsp 服务器中收到了来自 Android 应用程序的 HTTP POST,如何将该数据传递到 Javascript 函数中

javascript - 如何更改 <ul> 中的 <li> 值