Question

I'm trying to generate a single random number to append to my background image urls as a cache buster. The problem is, when I store the random number in a LESS variable it evaluates the javascript expression every time.

@randomNum: `Math.ceil(Math.random() * 100000)`;
div#div1{
    background: url("/assets/img/core/ui/document-flexpaper-sprite.png?lm=@{randomnum}");
}
div#div2{
    background: url("/assets/img/core/ui/document-flexpaper-sprite.png?lm=@{randomnum}");
}

Both divs will make requests to the image and they will have different random numbers. Should this be expected behavior? If so, does anyone know a way to store it and not evaluate it everytime so i have one same random number string to append to several calls to the same background image? thanks!

Was it helpful?

Solution

You can wrap the variable declaration into a mixin and it will be evaluated only once, e.g.:

.constRandom() {
    @randomNum: `Math.ceil(Math.random() * 100000)`;
} .constRandom();

div#div1{
    background: url("/assets/img/core/ui/document-flexpaper-sprite.png?lm=@{randomNum}");
}
div#div2{
    background: url("/assets/img/core/ui/document-flexpaper-sprite.png?lm=@{randomNum}");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top