File tree Expand file tree Collapse file tree 2 files changed +45
-1
lines changed Expand file tree Collapse file tree 2 files changed +45
-1
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change 1
1
@inherits RazorSlice <LayoutViewModel >
2
+ @using Elastic .Markdown .Helpers
2
3
<head >
3
4
<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 />
5
10
<meta charset =" utf-8" >
6
11
<meta name =" viewport" content =" width=device-width, initial-scale=1.0" >
7
12
@await RenderPartialAsync(_Favicon.Create())
You can’t perform that action at this time.
0 commit comments