singleton.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { getNonce } from 'get-nonce';
  2. function makeStyleTag() {
  3. if (!document)
  4. return null;
  5. const tag = document.createElement('style');
  6. tag.type = 'text/css';
  7. const nonce = getNonce();
  8. if (nonce) {
  9. tag.setAttribute('nonce', nonce);
  10. }
  11. return tag;
  12. }
  13. function injectStyles(tag, css) {
  14. // @ts-ignore
  15. if (tag.styleSheet) {
  16. // @ts-ignore
  17. tag.styleSheet.cssText = css;
  18. }
  19. else {
  20. tag.appendChild(document.createTextNode(css));
  21. }
  22. }
  23. function insertStyleTag(tag) {
  24. const head = document.head || document.getElementsByTagName('head')[0];
  25. head.appendChild(tag);
  26. }
  27. export const stylesheetSingleton = () => {
  28. let counter = 0;
  29. let stylesheet = null;
  30. return {
  31. add: (style) => {
  32. if (counter == 0) {
  33. if ((stylesheet = makeStyleTag())) {
  34. injectStyles(stylesheet, style);
  35. insertStyleTag(stylesheet);
  36. }
  37. }
  38. counter++;
  39. },
  40. remove: () => {
  41. counter--;
  42. if (!counter && stylesheet) {
  43. stylesheet.parentNode && stylesheet.parentNode.removeChild(stylesheet);
  44. stylesheet = null;
  45. }
  46. },
  47. };
  48. };