Skip to content

Instantly share code, notes, and snippets.

@lidlanca
Created September 22, 2014 22:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lidlanca/5a17d77ed8654d408e54 to your computer and use it in GitHub Desktop.
Save lidlanca/5a17d77ed8654d408e54 to your computer and use it in GitHub Desktop.
Onebox JS helper to load styles dynamically.
/*
Author: Lidlanca 2014
$.Onebox JS Helper
Usage
Load $.Onebox definition once.
In the onebox template use
$.Onebox.loadStyle("style_name",cssRule);
$.Onebox definition can be included in the code multiple times. it will not override it self.
styles can not be overwritten either unless removed first.
Styles tag are given a unique id based on a (prefix + style name)
Use a unique prefix to avoid ID collision.
Methods
loadStyle load new style if not already exists or loaded
removeStyle remove a previously loaded style from DOM
appendStyle append style to dom (used by LoadStyle Internally)
listLoadedStyles trace all styles in console
*/
(function ($){
if(!!$.Onebox) {return }
$.Onebox = new function (){
var loaded_styles = {};
var dom_id_prefix_ = "onebox_";
this.loadStyle = function(styleName,styleContent){
if (!loaded_styles.hasOwnProperty(styleName)){
loaded_styles[styleName] = {content:styleContent,added:false};
this.appendStyle(styleName);
} else {
if (loaded_styles[styleName].added == false){
console.log(styleContent);
loaded_styles[styleName].content = styleContent;
this.appendStyle(styleName);
} else {
//style already loaded
}
}
}
this.listLoadedStyles = function(){
console.log(loaded_styles);
}
this.removeStyle = function(styleName){
if (loaded_styles.hasOwnProperty(styleName)){
loaded_styles[styleName].added = false;
$("#" + dom_id_prefix_ +styleName).remove();
} else {
//style not exists
}
}
this.appendStyle = function (styleName){
if (!loaded_styles.hasOwnProperty(styleName)) return
loaded_styles[styleName].added = true;
var cssString = $("<style id='"+ dom_id_prefix_ + styleName + "'>" + loaded_styles[styleName].content + "</style>");
$("body").append(cssString);
}
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment