You are here

function advagg_mod_js_async_defer in Advanced CSS/JS Aggregation 8.2

Same name and namespace in other branches
  1. 7.2 advagg_mod/advagg_mod.module \advagg_mod_js_async_defer()

Add the defer and or the async tag to js.

Parameters

array $js: JS array.

1 call to advagg_mod_js_async_defer()
advagg_mod_js_alter in advagg_mod/advagg_mod.module
Implements hook_js_alter().

File

advagg_mod/advagg_mod.module, line 268
Advanced aggregation modifier module.

Code

function advagg_mod_js_async_defer(array &$js) {

  // Return early if this is disabled.
  $config = \Drupal::config('advagg_mod.settings');
  $defer = $config
    ->get('js_defer');
  $async = $config
    ->get('js_async');
  list($no_async_defer_list) = advagg_mod_get_lists();

  // Make all scripts defer and/or async.
  foreach ($js as $name => &$values) {
    $values['attributes'] = [];

    // Defer all scripts.
    if ($defer) {
      $values['attributes']['defer'] = TRUE;

      // Do not defer external scripts setting.
      if ($defer == 2 && $values['type'] === 'external') {
        unset($values['attributes']['defer']);
      }
    }

    // Async all scripts. On most browsers this will run instead of defer.
    // On some older browsers if defer is also set they will run that instead
    // if they don't support async.
    if ($async) {
      $values['attributes']['async'] = TRUE;
    }

    // No async defer list.
    foreach ($no_async_defer_list as $search_string) {
      if (strpos($name, $search_string) !== FALSE) {

        // Do not defer/async the loading this script.
        if ($defer) {
          unset($values['attributes']['async'], $values['attributes']['defer']);
        }
      }
    }
  }
  unset($values);
}