Last active
June 3, 2017 06:33
-
-
Save dekassegui/0296b35635d30305283fe7500fdaf4e9 to your computer and use it in GitHub Desktop.
Gestor de persistência de CSS temáticas.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Gestor de persistência de folhas de estilo temáticas. | |
*/ | |
function StyleSwitcher() { | |
var self = this; | |
var links = $("link[rel$='stylesheet'][title]").toArray().map($); | |
function search(callback) { | |
var a = links.find(callback); | |
return (a === undefined) ? null : a.attr("title"); | |
} | |
this.getActiveStyleSheet = function () { | |
return search( | |
function (a) { return !a.prop("disabled"); } | |
); | |
}; | |
this.getPreferredStyleSheet = function() { | |
return search( | |
function (a) { return !a.attr("rel").startsWith("alternate"); } | |
); | |
}; | |
this.setActiveStyleSheet = function (title) { | |
links.forEach( | |
function (a) { a.prop("disabled", a.attr("title") != title); } | |
); | |
}; | |
function isValid(title) { | |
return title && links.some( | |
function (a) { return a.attr("title") == title; }); | |
} | |
this.save = function (title) { | |
localStorage.setItem("style", | |
isValid(title) ? title : self.getActiveStyleSheet()); | |
}; | |
this.load = function () { return localStorage.getItem("style"); }; | |
/** | |
* Cache "persistente" do título da folha de estilo ativa. | |
*/ | |
window.addEventListener("unload", function () { self.save(); }, true); | |
/** | |
* Ativa a folha de estilo preferencial se não há título válido em cache. | |
*/ | |
( | |
function (title) { | |
self.setActiveStyleSheet( | |
isValid(title) ? title : self.getPreferredStyleSheet().attr("title")); | |
} | |
)(self.load()); | |
return this; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Implementação via jQuery.