index.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. var containers = []; // will store container HTMLElement references
  2. var styleElements = []; // will store {prepend: HTMLElement, append: HTMLElement}
  3. var usage = 'insert-css: You need to provide a CSS string. Usage: insertCss(cssString[, options]).';
  4. function insertCss(css, options) {
  5. options = options || {};
  6. if (css === undefined) {
  7. throw new Error(usage);
  8. }
  9. var position = options.prepend === true ? 'prepend' : 'append';
  10. var container = options.container !== undefined ? options.container : document.querySelector('head');
  11. var containerId = containers.indexOf(container);
  12. // first time we see this container, create the necessary entries
  13. if (containerId === -1) {
  14. containerId = containers.push(container) - 1;
  15. styleElements[containerId] = {};
  16. }
  17. // try to get the correponding container + position styleElement, create it otherwise
  18. var styleElement;
  19. if (styleElements[containerId] !== undefined && styleElements[containerId][position] !== undefined) {
  20. styleElement = styleElements[containerId][position];
  21. } else {
  22. styleElement = styleElements[containerId][position] = createStyleElement();
  23. if (position === 'prepend') {
  24. container.insertBefore(styleElement, container.childNodes[0]);
  25. } else {
  26. container.appendChild(styleElement);
  27. }
  28. }
  29. // strip potential UTF-8 BOM if css was read from a file
  30. if (css.charCodeAt(0) === 0xFEFF) { css = css.substr(1, css.length); }
  31. // actually add the stylesheet
  32. if (styleElement.styleSheet) {
  33. styleElement.styleSheet.cssText += css
  34. } else {
  35. styleElement.textContent += css;
  36. }
  37. return styleElement;
  38. };
  39. function createStyleElement() {
  40. var styleElement = document.createElement('style');
  41. styleElement.setAttribute('type', 'text/css');
  42. return styleElement;
  43. }
  44. module.exports = insertCss;
  45. module.exports.insertCss = insertCss;