Skip to content

Instantly share code, notes, and snippets.

@w3core
Created January 26, 2016 17:54
Show Gist options
  • Save w3core/affd602f31190f94f4a5 to your computer and use it in GitHub Desktop.
Save w3core/affd602f31190f94f4a5 to your computer and use it in GitHub Desktop.
This plugin extends Less.JS processor for "attach(url)" and "detach(url)" methods, that allows dynamically attach/detach ".less" files to document.
/**
* Attach LESS file: less.attach(url)
* Detach LESS file: less.detach(url)
*/
(new function(){
if (typeof less == "undefined") less = {sheets:[], refresh:function(){}};
function extractId (href) {
return href.replace(/^[a-z]+:\/\/?[^\/]+/, '' ) // Remove protocol & domain
.replace(/^\//, '' ) // Remove root /
.replace(/\?.*$/, '' ) // Remove query
.replace(/\.[^\.\/]+$/, '' ) // Remove file extension
.replace(/[^\.\w-]+/g, '-') // Replace illegal characters
.replace(/\./g, ':'); // Replace dots with colons(for valid id)
}
function getId (sheet) {
var href = sheet.href ? sheet.href.replace(/\?.*$/, '') : '';
var id = 'less:' + (sheet.title || extractId(href));
return id;
}
function toLink (url) {
if (typeof url == "string") {
var link = document.createElement("link");
link.rel = "stylesheet/less";
link.href = url;
}
return link || url;
}
function getIndex (url) {
var link = toLink(url);
var index = -1;
for (var i=0; i<less.sheets.length; i++) {
if (less.sheets[i].href == link.href || less.sheets[i].title == link.title) {
index = i;
break;
}
}
return index;
}
function attach (url) {
var link = toLink(url);
var index = getIndex(link);
if (index < 0) {
less.sheets.push(link);
less.refresh();
}
return link;
}
function detach (url) {
var link = toLink(url);
var index = getIndex(link);
if (index >= 0) less.sheets.splice(index, 1);
var node = document.getElementById(getId(link));
if (node) node.parentNode.removeChild(node);
return link;
}
less.attach = attach;
less.detach = detach;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment