Skip to content

Commit 99b12f8

Browse files
authored
Preload fonts in use as per CSS definitions (#765)
* Preload fonts in use as per CSS definitions * Adjust FontUriCache typing and stricten Regex * Readjust link header ordering. * Fix accessor to private.
1 parent f4983fa commit 99b12f8

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Licensed to Elasticsearch B.V under one or more agreements.
2+
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
3+
// See the LICENSE file in the project root for more information
4+
5+
using System.Collections.Immutable;
6+
using System.Diagnostics;
7+
using System.Reflection;
8+
using System.Text.RegularExpressions;
9+
10+
namespace Elastic.Markdown.Helpers;
11+
12+
public static partial class FontPreloader
13+
{
14+
private static IReadOnlyCollection<string>? FontUriCache = null!;
15+
16+
public static async Task<IReadOnlyCollection<string>> GetFontUrisAsync() => FontUriCache ??= await LoadFontUrisAsync();
17+
private static async Task<IReadOnlyCollection<string>> LoadFontUrisAsync()
18+
{
19+
var cachedFontUris = new List<string>();
20+
var assembly = Assembly.GetExecutingAssembly();
21+
var stylesResourceName = assembly.GetManifestResourceNames().First(n => n.EndsWith("styles.css"));
22+
23+
using var cssFileStream = new StreamReader(assembly.GetManifestResourceStream(stylesResourceName)!);
24+
25+
var cssFile = await cssFileStream.ReadToEndAsync();
26+
var matches = FontUriRegex().Matches(cssFile);
27+
28+
foreach (Match match in matches)
29+
{
30+
if (match.Success)
31+
cachedFontUris.Add($"/_static/{match.Groups[1].Value}");
32+
}
33+
FontUriCache = cachedFontUris;
34+
return FontUriCache;
35+
}
36+
37+
[GeneratedRegex(@"url\([""']?([^""'\)]+?\.(woff2|ttf|otf))[""']?\)", RegexOptions.Multiline | RegexOptions.Compiled)]
38+
private static partial Regex FontUriRegex();
39+
}

src/Elastic.Markdown/Slices/Layout/_Head.cshtml

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
@inherits RazorSlice<LayoutViewModel>
2+
@using Elastic.Markdown.Helpers
23
<head>
34
<title>@Model.Title</title>
4-
<link rel="stylesheet" type="text/css" href="@Model.Static("styles.css")"/>
5+
@foreach (var fontFile in await FontPreloader.GetFontUrisAsync())
6+
{
7+
<link rel="preload" href="@fontFile" as="font" type="font/woff2" crossorigin>
8+
}
9+
<link rel="stylesheet preload" as="style" type="text/css" href="@Model.Static("styles.css")" crossorigin/>
510
<meta charset="utf-8">
611
<meta name="viewport" content="width=device-width, initial-scale=1.0">
712
@await RenderPartialAsync(_Favicon.Create())

0 commit comments

Comments
 (0)