LESS CSS with custom javascript function for cookieless domain

I would like to use less ( http://lesscss.org/ ) instead of sass ( http://sass-lang.com/ ) for css preprocessing. I have a cookieless cookie set for static resources. For example: 0.mydomain.com, 1.mydomain.com, 2.mydomain.com, etc. I would like to compile CSS using less so that cookieless domains are injected into compiled CSS output. I found this ability to create custom functions in sass docs using @function. Is there an equivalent for less (I can't find)? I need a function that performs a hash algorithm to convert a file name to an X number corresponding to a file without cooki (X.mydomain.com). How to do it using less?

The following is an example to illustrate:

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')) } 

which generated compiled output

 .myItem {background-image:url('http://1.mydomain.com/images/background.jpg') } 

SASS example http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#functions

See Function Directives

The closest example from the LESS docs is below, but there is no function to build the base url.

 @base-url: "http://assets.fnord.com"; background-image: url("@{base-url}/images/bg.png"); 

Perhaps there is part of the LESS + Node.js solution?

Thanks!

+4
source share
2 answers

No. LESS has significantly fewer features than Sass (no functions, no loops). You will need to use a mixin to do something like this remotely. Sass could do this, except for the fact that it has no built-in string manipulation functions, so you need to write some Ruby code to add those that are in.

+1
source

You must do this using the LeSS ability to insert 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"); } 

I don’t know what the performance will be, but then, if you are processing the server side, you do not care, and the client side caches, so there should not be a problem.

+6
source

Source: https://habr.com/ru/post/1436994/


All Articles