|
8 | 8 | import {Injectable} from '@angular/core';
|
9 | 9 | import {Platform} from '@angular/cdk/platform';
|
10 | 10 |
|
11 |
| -/** |
12 |
| - * Global registry for all dynamically-created, injected style tags. |
13 |
| - */ |
14 |
| -const styleElementForWebkitCompatibility: Map<string, HTMLStyleElement> = new Map(); |
| 11 | +/** Global registry for all dynamically-created, injected media queries. */ |
| 12 | +const mediaQueriesForWebkitCompatibility: Set<string> = new Set<string>(); |
| 13 | + |
| 14 | +/** Style tag that holds all of the dynamically-created media queries. */ |
| 15 | +let mediaQueryStyleNode: HTMLStyleElement | undefined; |
15 | 16 |
|
16 | 17 | /** A utility for calling matchMedia queries. */
|
17 | 18 | @Injectable({providedIn: 'root'})
|
@@ -42,27 +43,28 @@ export class MediaMatcher {
|
42 | 43 | }
|
43 | 44 |
|
44 | 45 | /**
|
45 |
| - * For Webkit engines that only trigger the MediaQueryListListener when there is at least one CSS |
46 |
| - * selector for the respective media query. |
| 46 | + * For Webkit engines that only trigger the MediaQueryListListener when |
| 47 | + * there is at least one CSS selector for the respective media query. |
47 | 48 | */
|
48 | 49 | function createEmptyStyleRule(query: string) {
|
49 |
| - if (!styleElementForWebkitCompatibility.has(query)) { |
50 |
| - try { |
51 |
| - const style = document.createElement('style'); |
52 |
| - |
53 |
| - style.setAttribute('type', 'text/css'); |
54 |
| - if (!style.sheet) { |
55 |
| - const cssText = `@media ${query} {.fx-query-test{ }}`; |
56 |
| - style.appendChild(document.createTextNode(cssText)); |
57 |
| - } |
| 50 | + if (mediaQueriesForWebkitCompatibility.has(query)) { |
| 51 | + return; |
| 52 | + } |
58 | 53 |
|
59 |
| - document.getElementsByTagName('head')[0].appendChild(style); |
| 54 | + try { |
| 55 | + if (!mediaQueryStyleNode) { |
| 56 | + mediaQueryStyleNode = document.createElement('style'); |
| 57 | + mediaQueryStyleNode.setAttribute('type', 'text/css'); |
| 58 | + document.head.appendChild(mediaQueryStyleNode); |
| 59 | + } |
60 | 60 |
|
61 |
| - // Store in private global registry |
62 |
| - styleElementForWebkitCompatibility.set(query, style); |
63 |
| - } catch (e) { |
64 |
| - console.error(e); |
| 61 | + if (mediaQueryStyleNode.sheet) { |
| 62 | + (mediaQueryStyleNode.sheet as CSSStyleSheet) |
| 63 | + .insertRule(`@media ${query} {.fx-query-test{ }}`, 0); |
| 64 | + mediaQueriesForWebkitCompatibility.add(query); |
65 | 65 | }
|
| 66 | + } catch (e) { |
| 67 | + console.error(e); |
66 | 68 | }
|
67 | 69 | }
|
68 | 70 |
|
|
0 commit comments