css.js 1.9 KB

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