Skip to content

Instantly share code, notes, and snippets.

@bmatusiak bmatusiak/css.js
Created Nov 5, 2012

Embed
What would you like to do?
requirejs plugin
syntax is going to be 
var css = require("css!./main.css");
css.load();//<-- loads to head
css.unload();//<-- removes element from any parent it has
css.element; //<-- element 
css.text; //<-- textContent
define(function() {
function css(file) {
this._file = file;
this.element = css.lookfor(this._file);
if (!this.element) {
this.element = document.createElement("link");
this.element.setAttribute("rel", "stylesheet");
this.element.setAttribute("type", "text/css");
this.element.setAttribute("href", this._file);
}
}
css.head = function() {
return document.getElementsByTagName("head")[0];
};
css.lookfor = function(file) {
var allsuspects = document.getElementsByTagName("link");
for (var i = allsuspects.length; i >= 0; i--) {
if (allsuspects[i] && allsuspects[i].getAttribute("href") !== null && allsuspects[i].getAttribute("href").indexOf(file) != -1) return allsuspects[i];
}
return false;
};
css.prototype.load = function loadCSS() {
css.head().appendChild(this.element);
return this;
};
css.prototype.unload = function unloadCSS() {
this.element.parentNode.removeChild(this.element);
return this;
};
//API
return {
load: function(name, req, onLoad, config) {
var url = req.toUrl(name);
url.substr(0, url.length - 3);
var cssObject = new css(url);
req(['text!' + cssObject._file], function(theText) {
cssObject.text = theText;
onLoad(cssObject);
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.