UNPKG

new-themes-switch

Version:

Toolset for switch multiple themes in application based on webpack

62 lines (50 loc) 1.33 kB
"use strict"; var THEME_KEY = 'theme'; var PLUGIN_KEY = 'pkey'; var PLUGIN_VALUE = 'themes-switch'; function changeTheme(theme, themeUrl, onLoad) { var container = document.html || document.getElementsByTagName('html')[0]; var links = container.getElementsByTagName('link'); var oldTheme; if (links && links.length > 0) { for (var i = 0; i < links.length; i++) { if (getAttribute(links[i], PLUGIN_KEY) === PLUGIN_VALUE) { oldTheme = links[i]; break; } } } var link = document.createElement('link'); link.rel = 'stylesheet'; link.href = themeUrl; setAttribute(link, THEME_KEY, theme); setAttribute(link, PLUGIN_KEY, PLUGIN_VALUE); container.appendChild(link); link.onload = function () { removeNode(oldTheme); if (onLoad) { onLoad(link); } }; } function removeNode(node) { if (node && node.parentNode) { node.parentNode.removeChild(node); } } function getAttribute(element, key) { if (element.dataset) { return element.dataset[key]; } return element.getAttribute(key); } function setAttribute(element, key, value) { if (element.dataset) { element.dataset[key] = value; } else { element.setAttribute(key, value); } } module.exports = { changeTheme: changeTheme // eslint-disable-line object-shorthand };