@@ -26,6 +26,8 @@ import { makePathFromDrawOPS } from "./display_utils.js";
2626class FontLoader {
2727 #systemFonts = new Set ( ) ;
2828
29+ #styleSheet = null ;
30+
2931 constructor ( {
3032 ownerDocument = globalThis . document ,
3133 styleElement = null , // For testing only.
@@ -55,14 +57,38 @@ class FontLoader {
5557 }
5658
5759 insertRule ( rule ) {
60+ const styleSheet = this . #getStyleSheet( ) ;
61+ styleSheet . insertRule ( rule , styleSheet . cssRules . length ) ;
62+ }
63+
64+ #getStyleSheet( ) {
65+ if ( this . #styleSheet) {
66+ return this . #styleSheet;
67+ }
68+
69+ // Constructable stylesheets aren't blocked by CSP inline-style checks.
70+ // Use the constructor from the document's own window, since
71+ // `this._document` may belong to a different window (e.g. a print iframe)
72+ // and a constructable stylesheet can only be adopted by the document it was
73+ // created for.
74+ const StyleSheet =
75+ this . _document . defaultView ?. CSSStyleSheet || globalThis . CSSStyleSheet ;
76+ if ( ! this . styleElement && StyleSheet ) {
77+ const { adoptedStyleSheets } = this . _document ;
78+ if ( adoptedStyleSheets ) {
79+ const styleSheet = new StyleSheet ( ) ;
80+ adoptedStyleSheets . push ( styleSheet ) ;
81+ return ( this . #styleSheet = styleSheet ) ;
82+ }
83+ }
84+
5885 if ( ! this . styleElement ) {
5986 this . styleElement = this . _document . createElement ( "style" ) ;
6087 this . _document . documentElement
6188 . getElementsByTagName ( "head" ) [ 0 ]
6289 . append ( this . styleElement ) ;
6390 }
64- const styleSheet = this . styleElement . sheet ;
65- styleSheet . insertRule ( rule , styleSheet . cssRules . length ) ;
91+ return ( this . #styleSheet = this . styleElement . sheet ) ;
6692 }
6793
6894 clear ( ) {
@@ -72,6 +98,16 @@ class FontLoader {
7298 this . nativeFontFaces . clear ( ) ;
7399 this . #systemFonts. clear ( ) ;
74100
101+ if ( this . #styleSheet) {
102+ const { adoptedStyleSheets } = this . _document ;
103+ if ( adoptedStyleSheets ?. includes ( this . #styleSheet) ) {
104+ this . _document . adoptedStyleSheets = adoptedStyleSheets . filter (
105+ styleSheet => styleSheet !== this . #styleSheet
106+ ) ;
107+ }
108+ this . #styleSheet = null ;
109+ }
110+
75111 if ( this . styleElement ) {
76112 // Note: ChildNode.remove doesn't throw if the parentNode is undefined.
77113 this . styleElement . remove ( ) ;
0 commit comments