在线上环境中, 经常会有多个cdn 地址来加速静态资源的加载, 对于模板文件中的js, css, img 都可以通过后端的helper方法在render时分配,
但是在css 中也会有url地址, 比如 font-face, background-image: url(), 这里的信息是静态的, 所以需要在scss文件转换的时候做处理。
这里的前提是cdn域名列表内容比较固定, 不会经常变更。
sampleCDN内容很简单, 每次随机一个地址。
@function sampleCDN() {
$cdn: 'http://cdn1.com', 'http://cdn2.com', 'http://cdn3.com';
$nth: nth($cdn, random(length($cdn)));
@return $nth
}
.img-a {
background-image: url('#{sampleCDN()}/hello.png');
}
.img-b {
background-image: url('#{sampleCDN()}/hello.png');
}
.img-c {
background-image: url('#{sampleCDN()}/hello.png');
}
.img-d {
background-image: url('#{sampleCDN()}/hello.png');
}
.img-e {
background-image: url('#{sampleCDN()}/hello.png');
}
输出:
.img-a {
background-image: url("http://cdn2.com/hello.png"); }
.img-b {
background-image: url("http://cdn2.com/hello.png"); }
.img-c {
background-image: url("http://cdn3.com/hello.png"); }
.img-d {
background-image: url("http://cdn3.com/hello.png"); }
.img-e {
background-image: url("http://cdn1.com/hello.png"); }