css_loader.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. const waitSeconds = 100;
  2. const head = document.getElementsByTagName('head')[0];
  3. // get all link tags in the page
  4. const links = document.getElementsByTagName('link');
  5. const linkHrefs = [];
  6. for (let i = 0; i < links.length; i++) {
  7. linkHrefs.push(links[i].href);
  8. }
  9. const isWebkit = !!window.navigator.userAgent.match(/AppleWebKit\/([^ ;]*)/);
  10. const webkitLoadCheck = (link, callback) => {
  11. setTimeout(() => {
  12. for (let i = 0; i < document.styleSheets.length; i++) {
  13. const sheet = document.styleSheets[i];
  14. if (sheet.href === link.href) {
  15. return callback();
  16. }
  17. }
  18. webkitLoadCheck(link, callback);
  19. }, 10);
  20. };
  21. const noop = () => {};
  22. const loadCSS = url => {
  23. return new Promise((resolve, reject) => {
  24. const link = document.createElement('link');
  25. const timeout = setTimeout(() => {
  26. reject('Unable to load CSS');
  27. }, waitSeconds * 1000);
  28. const _callback = error => {
  29. clearTimeout(timeout);
  30. link.onload = link.onerror = noop;
  31. setTimeout(() => {
  32. if (error) {
  33. reject(error);
  34. } else {
  35. resolve('');
  36. }
  37. }, 7);
  38. };
  39. link.type = 'text/css';
  40. link.rel = 'stylesheet';
  41. link.href = url;
  42. if (!isWebkit) {
  43. link.onload = () => {
  44. _callback(undefined);
  45. };
  46. } else {
  47. webkitLoadCheck(link, _callback);
  48. }
  49. link.onerror = (evt: any) => {
  50. _callback(evt.error || new Error('Error loading CSS file.'));
  51. };
  52. head.appendChild(link);
  53. });
  54. };
  55. export function fetch(load): any {
  56. if (typeof window === 'undefined') {
  57. return '';
  58. }
  59. // don't reload styles loaded in the head
  60. for (let i = 0; i < linkHrefs.length; i++) {
  61. if (load.address === linkHrefs[i]) {
  62. return '';
  63. }
  64. }
  65. return loadCSS(load.address);
  66. }