UNPKG

isomorphic-style-loader

Version:

CSS style loader for Webpack optimized for critical path CSS rendering and isomoprhic web apps

97 lines (92 loc) 2.75 kB
/*! Isomorphic Style Loader | MIT License | https://github.com/kriasoft/isomorphic-style-loader */ 'use strict'; function createUniqueIdentifiers(identifiers) { var dupeCount = Object.create(null); return identifiers.map(function (identifier) { if (typeof dupeCount[identifier] !== 'undefined') { dupeCount[identifier] += 1; } else { dupeCount[identifier] = 0; } return dupeCount[identifier] === 0 ? "" + identifier : identifier + "_" + dupeCount[identifier]; }); } var inserted = Object.create(null); function b64EncodeUnicode(str) { return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) { return String.fromCharCode(parseInt(p1, 16)); })); } function removeCss(ids) { ids.forEach(function (id) { if (--inserted[id] <= 0) { delete inserted[id]; var elem = document.getElementById(id); if (elem) { elem.parentNode.removeChild(elem); } } }); } function insertCss(styles, _temp) { var _ref = _temp === void 0 ? {} : _temp, _ref$replace = _ref.replace, replace = _ref$replace === void 0 ? false : _ref$replace, _ref$prepend = _ref.prepend, prepend = _ref$prepend === void 0 ? false : _ref$prepend, _ref$prefix = _ref.prefix, prefix = _ref$prefix === void 0 ? 's' : _ref$prefix; var ids = []; var identifiers = createUniqueIdentifiers(styles.map(function (_ref2) { var moduleId = _ref2[0]; return moduleId; })); for (var i = 0; i < styles.length; i++) { var _styles$i = styles[i], css = _styles$i[1], media = _styles$i[2], sourceMap = _styles$i[3]; var id = "" + prefix + identifiers[i]; if (inserted[id]) { if (!replace) { inserted[id]++; ids.push(id); continue; } } else { inserted[id] = 1; ids.push(id); } var elem = document.getElementById(id); var create = false; if (!elem) { create = true; elem = document.createElement('style'); elem.id = id; if (media) { elem.setAttribute('media', media); } } var cssText = css; if (sourceMap) { cssText += "\n/*# sourceMappingURL=data:application/json;base64," + b64EncodeUnicode(JSON.stringify(sourceMap)) + "*/"; cssText += "\n/*# sourceURL=" + sourceMap.file + "?" + id + "*/"; } elem.textContent = cssText; if (create) { if (prepend) { document.head.insertBefore(elem, document.head.childNodes[0]); } else { document.head.appendChild(elem); } } } var removed = false; return function () { if (removed) return; removed = true; removeCss(ids); }; } module.exports = insertCss; //# sourceMappingURL=insertCss.js.map