@@ -4,6 +4,8 @@ let sparkleTemplate;
44// https://caniuse.com/mdn-api_cssstylesheet_replacesync
55const supportsConstructibleStylesheets = ( "replaceSync" in CSSStyleSheet . prototype ) ;
66
7+ const motionOK = window . matchMedia ( '(prefers-reduced-motion: no-preference)' ) ;
8+
79class SparklyText extends HTMLElement {
810 #numberOfSparkles = 3 ;
911 #sparkleSvg = `<svg width="1200" height="1200" viewBox="0 0 1200 1200" aria-hidden="true">
@@ -77,19 +79,21 @@ class SparklyText extends HTMLElement {
7779 }
7880
7981 connectedCallback ( ) {
80- if ( this . shadowRoot ) {
81- return ;
82- }
82+ const needsSparkles = motionOK . matches || ! this . shadowRoot ;
8383
84- this . #numberOfSparkles = parseInt (
85- this . getAttribute ( "number-of-sparkles" ) || `${ this . #numberOfSparkles} ` ,
86- 10
87- ) ;
84+ if ( ! this . shadowRoot ) {
85+ this . attachShadow ( { mode : "open" } ) ;
86+ this . generateCss ( ) ;
87+ this . shadowRoot . append ( document . createElement ( "slot" ) ) ;
88+ }
8889
89- this . attachShadow ( { mode : "open" } ) ;
90- this . shadowRoot . append ( document . createElement ( "slot" ) ) ;
91- this . generateCss ( ) ;
92- this . addSparkles ( ) ;
90+ if ( needsSparkles ) {
91+ this . #numberOfSparkles = parseInt (
92+ this . getAttribute ( "number-of-sparkles" ) || `${ this . #numberOfSparkles} ` ,
93+ 10
94+ ) ;
95+ this . addSparkles ( ) ;
96+ }
9397 }
9498
9599 addSparkles ( ) {
@@ -121,8 +125,7 @@ class SparklyText extends HTMLElement {
121125 } ) ;
122126
123127 setTimeout ( ( ) => {
124- const { matches :motionOK } = window . matchMedia ( '(prefers-reduced-motion: no-preference)' ) ;
125- if ( motionOK && this . isConnected ) this . addSparkle ( ) ;
128+ if ( motionOK . matches && this . isConnected ) this . addSparkle ( ) ;
126129 } , 2000 + Math . random ( ) * 1000 ) ;
127130 }
128131}
0 commit comments