LESS CSS with custom javascript function for cookieless domain
-
11-12-2019 - |
문제
I'd like to use less ( http://lesscss.org/ ) instead of sass ( http://sass-lang.com/ ) for preprocessing css. I have a set of cookieless domains for static resources. For example: 0.mydomain.com, 1.mydomain.com, 2.mydomain.com, etc. I would like to compile CSS using less such that the cookieless domains are injected into the compiled CSS output. I found this ability to to create custom functions in the sass docs using @function. Does the equivalent exist for less (I can not find)? I need a function that performs a hashing algorithm to convert a filename into a number X corresponding to a cookieless domain (X.mydomain.com). How would one do this using less?
The below example is contrived for illustration:
In my.less file:
@function domainX(path) {
//configs
var protocol = "http://";
var domain = ".mydomain.com"
var N = 4; //4 cookieless domains
var sum = 0;
var s = path.substr(path.lastIndexOf("/") + 1);
for (var i = 0; i < s.length; i++) {
sum += s[i].charCodeAt();
}
@return protocol + (sum % N) + domain + path;
}
.myItem {background-image:url(domainX('/images/background.jpg')) }
that would generate compiled output
.myItem {background-image:url('http://1.mydomain.com/images/background.jpg') }
The SASS example is http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#functions
See section "Function Directives"
The closest example from the LESS docs is below, but there's no function to construct the base-url.
@base-url: "http://assets.fnord.com";
background-image: url("@{base-url}/images/bg.png");
Maybe there is a LESS + Node.js part of the solution too?
Thanks!
해결책
No. LESS has considerably less features than Sass (no functions, no loops). You would have to use a mixin to do anything remotely like that. Sass could do it except for the fact that it doesn't have any string manipulation functions built in, so you'd have to write a bit of Ruby code to add those in.
다른 팁
You should be able to do this using LeSS' ability to embed js:
.background(@path) {
background-image: ~`(function(){ var protocol = "http://"; var domain = ".mydomain.com"; var N = 4; var sum = 0; var s = @{path}.substr(@{path}.lastIndexOf("/") + 1); for (var i = 0; i < s.length; i++) { sum += s[i].charCodeAt(); } return "url(" + protocol + (sum % N) + domain + @{path} + ")";})()`;
}
.myItem {
.background("/images/background.jpg");
}
no idea what the performance would be like, but then if you're processing server side you won't care, and client side it caches so shouldn't be a problem.