UNPKG

insert-style-link

Version:

Insert, switch or shift a stylesheet <link />

43 lines (42 loc) 1.67 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.switchStyleLink = exports.insertStyleLink = void 0; var links = typeof window === 'undefined' ? null : document.getElementsByTagName('link'); var insertStyleLink = function (url, _a) { var _b = _a === void 0 ? {} : _a, _c = _b.isSameLink, isSameLink = _c === void 0 ? function (link1, link2) { return link1 === link2; } : _c; var link = document.createElement('link'); link.href = url; var fullHref = link.href; link.type = 'text/css'; link.rel = 'stylesheet'; function unuse() { var _a; // prevent insertion duplication var maybeExistedLink = Array.from(links !== null && links !== void 0 ? links : []).find(function (l) { return isSameLink(l.href, fullHref); }); if (maybeExistedLink) (_a = maybeExistedLink.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(maybeExistedLink); if (document.head.contains(link)) document.head.removeChild(link); } function use() { // clear unuse(); document.head.appendChild(link); } return { use: use, unuse: unuse }; }; exports.insertStyleLink = insertStyleLink; var switchStyleLink = function (option) { if (option === void 0) { option = {}; } var insertIns; function unuse() { insertIns === null || insertIns === void 0 ? void 0 : insertIns.unuse(); } function use(link) { unuse(); insertIns = (0, exports.insertStyleLink)(link, option); insertIns.use(); } return { use: use, unuse: unuse }; }; exports.switchStyleLink = switchStyleLink;