Skip to content

Instantly share code, notes, and snippets.

@dekassegui
Last active June 3, 2017 06:33
Show Gist options
  • Save dekassegui/0296b35635d30305283fe7500fdaf4e9 to your computer and use it in GitHub Desktop.
Save dekassegui/0296b35635d30305283fe7500fdaf4e9 to your computer and use it in GitHub Desktop.
Gestor de persistência de CSS temáticas.
/**
* 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;
}
@dekassegui
Copy link
Author

Implementação via jQuery.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment