【问题标题】:Drupal 7: how do I add the async attribute to an external JS script when using drupal_add_js?Drupal 7:使用 drupal_add_js 时如何将 async 属性添加到外部 JS 脚本?
【发布时间】:2018-11-12 05:34:36
【问题描述】:

我试过了:

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

没有结果。

有谁知道我是怎么做到的吗?

【问题讨论】:

    标签: javascript drupal drupal-7 drupal-hooks


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 2021-05-14
      • 2021-03-26
      • 2022-10-24
      • 2021-01-16
      • 1970-01-01
      相关资源
      最近更新 更多