Cache busting images which are linked inside SASS files

情到浓时终转凉″ 提交于 2019-12-04 00:27:54

As you're using SASS, it's possible to define a custom variable in your SASS files which could be used for cache busting, and then append that variable to any image url paths.

The variable just needs to hold a reference to the current timestamp.

To do this, you'll need to create a new function in SASS to expose a timestamp, which can be done as follows:

module Sass::Script::Functions
    def timestamp()
        return Sass::Script::String.new(Time.now.strftime("%Y%m%d%H%M"))
    end
end

Then you can access the timestamp as follows:

$cacheVersion = timestamp()

.someClass {
    background-image: url('your/path/file.jpg?cacheversion='$cacheVersion);
}

When compiled, this will produce something like:

.someClass {
    background-image: url('your/path/file.jpg?cacheversion=201510091349');
}

Using the answer from @Amo for inspiration, the solution I ended up using was a mixin, which makes use of the unique_id() function to generate a random value. This avoids having to define a custom SASS function, so it's simpler and as @Amelia pointed out, a bit cleaner too.

The mixin

@mixin background-cache-bust($url) {
    background-image: #{'url('} + $url + #{'?v='} + unique_id() + #{')'};
}

Example

.sprite {
    @include background-cache-bust('/build/images/common/sprite.png');
}

Result

.sprite {
    background-image: "url(/build/images/common/sprite.png?v=u95ab40e0)";
}

I'm using gulp-sass and @AJReading mixin doesn't concantenate string correctly, which compiles to:

background-image: url(+ "$url" + ?v= + u2f58eec1 + );

Here is what works in my case

Mixin

@mixin background-cache-bust($url) {
   background-image: unquote('url(' + $url + '?v=' + unique_id() + ')');
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!