使用sass random 函數隨機分配cdn hostname
阿新 • • 發佈:2017-05-11
輸出 資源 cdn nbsp rand 轉換 加速 func image
在線上環境中, 經常會有多個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"); }
使用sass random 函數隨機分配cdn hostname