|
1 | 1 | import {NgModule, isDevMode} from '@angular/core'; |
2 | 2 |
|
| 3 | +/** Whether the theme presence has already been checked. */ |
| 4 | +let hasBeenChecked = false; |
| 5 | + |
3 | 6 | /** |
4 | 7 | * Module that verifies that the user has loaded the core theming file, |
5 | 8 | * without which most Material module won't work as expected. |
| 9 | + * |
| 10 | + * Note on testing methodology: A more efficient way to check for the theme |
| 11 | + * would be to loop through the `document.styleSheets`, however most browsers |
| 12 | + * don't expose the stylesheet rules, if the file was loaded from another domain. |
| 13 | + * This would trigger false positives if the theme is being loaded from a CDN. |
| 14 | + * |
6 | 15 | * @docs-private |
7 | 16 | */ |
8 | 17 | @NgModule() |
9 | 18 | export class MdThemeCheckModule { |
10 | 19 | constructor() { |
11 | | - if (!isDevMode() || typeof document === 'undefined') { |
| 20 | + if (hasBeenChecked || typeof document === 'undefined' || !isDevMode()) { |
12 | 21 | return; |
13 | 22 | } |
14 | 23 |
|
15 | | - for (let i = 0; i < document.styleSheets.length; i++) { |
16 | | - // The try/catch is needed, because some browsers can throw a security |
17 | | - // error when accessing the `cssRules` from another domain. |
18 | | - try { |
19 | | - let rules = (document.styleSheets.item(i) as CSSStyleSheet).cssRules; |
| 24 | + let testElement = document.createElement('div'); |
20 | 25 |
|
21 | | - if (rules) { |
22 | | - for (let j = 0; j < rules.length; j++) { |
23 | | - let selector = (rules.item(j) as CSSStyleRule).selectorText; |
| 26 | + testElement.classList.add('md-theme-loaded-marker'); |
| 27 | + document.body.appendChild(testElement); |
24 | 28 |
|
25 | | - if (selector && selector.includes('.md-theme-loaded-marker')) { |
26 | | - return; |
27 | | - } |
28 | | - } |
29 | | - } |
30 | | - } catch (e) { } |
| 29 | + if (getComputedStyle(testElement).display !== 'none') { |
| 30 | + console.warn( |
| 31 | + 'Could not find Angular Material core theme. Most Material ' + |
| 32 | + 'components may not work as expected. For more info refer ' + |
| 33 | + 'to the theming guide: https://github.com/angular/material2/blob/master/guides/theming.md' |
| 34 | + ); |
31 | 35 | } |
32 | 36 |
|
33 | | - console.warn( |
34 | | - 'Could not find Angular Material core theme. Most Material ' + |
35 | | - 'components may not work as expected. For more info refer ' + |
36 | | - 'to the theming guide: https://github.com/angular/material2/blob/master/guides/theming.md' |
37 | | - ); |
| 37 | + document.body.removeChild(testElement); |
| 38 | + hasBeenChecked = true; |
38 | 39 | } |
39 | 40 | } |
0 commit comments