Commit 4cf401b9 authored by Ivica Puljic's avatar Ivica Puljic Committed by Ivica Puljic
Browse files

Issue #3247543 by pivica, Berdir: Add fonts preloading support

parent ce84c834
Loading
Loading
Loading
Loading
+57 −0
Original line number Diff line number Diff line
@@ -22,6 +22,16 @@ function bs_base_theme_suggestions_page_alter(array &$suggestions, array $variab
  }
}

/**
 * Implements hook_page_attachments_alter().
 */
function bs_base_page_attachments_alter(&$attachments) {
  $active_theme = \Drupal::theme()->getActiveTheme();
  if (!empty($active_theme->getExtension()->info['preload-fonts']) && is_array($active_theme->getExtension()->info['preload-fonts'])) {
    bs_base_preload_fonts($active_theme->getExtension()->info['preload-fonts'], $attachments);
  }
}

/**
 * Implements hook__theme_suggestions_HOOK_alter() for form element.
 */
@@ -112,3 +122,50 @@ function bs_base_preprocess_maintenance_page(&$variables) {
    $variables['maintenance_image_path'] = file_url_transform_relative(file_create_url($maintenance_image['path']));
  }
}

/* Helpers */

/**
 * Adds fonts preload links to head section.
 *
 * For more info visit next resources:
 * - @see https://www.freecodecamp.org/news/web-fonts-in-2018-f191a48367e8/#preload-fonts
 * - @see https://web.dev/preload-optional-fonts/
 *
 * @param array $fonts
 *   An array of fonts paths to be preloaded.
 * @param array $attachments
 *   An array of page attachments.
 */
function bs_base_preload_fonts(array $fonts, array &$attachments) {
  foreach ($fonts as $font) {
    // Support relative font path from root like '/libraries/.../....woff2' or
    // remote font paths.
    if (strpos($font, '/') === 0 || strpos($font, 'http') === 0) {
      $uri = $font;
    }
    // Support twig expansion syntax like @custom_theme/fonts/font1.woff.
    elseif (preg_match('/^\@([^\/]+)(\/.+)$/', $font, $match)) {
      $uri = drupal_get_path('theme', $match[1]) . $match[2];
    }
    // Support relative font path from the current active theme.
    elseif (strpos($font, '/') !== 0) {
      $active_theme = \Drupal::theme()->getActiveTheme();
      $uri = $active_theme->getPath() . '/' . $font;
    }
    // Font path pattern is not recognized, skip it.
    else {
      continue;
    }

    $attachments['#attached']['html_head_link'][] = [[
      'rel' => 'preload',
      'as' => 'font',
      // @todo this two functions are depreciated in Drupal 9.3, fix it later.
      // @see https://www.drupal.org/node/2940031
      'href' => file_url_transform_relative(file_create_url($uri)),
      'type' => 'font/' . pathinfo($font, PATHINFO_EXTENSION),
      'crossorigin' => 'anonymous',
    ], FALSE];
  }
}