AJReading AJReading - 1 year ago 111
Sass (Sass) Question

Cache busting images which are linked inside SASS files

I'm fairly new to Laravel 5.0, but not to PHP. I've been playing around with Elixir to compile my SASS, copy images from my resource directory and run them through the

function to prevent caching.

This works great for CSS, images and JavaScript, however; is it possible to have Elixir cache-bust the images linked in my CSS/SASS as well? Sure it's easily enough to version the images but is there a way of adjusting the CSS to reflect the new filenames?

I discovered this: https://github.com/trentearl/gulp-css-url-adjuster
which allows you to append a query parameter to the file paths in a CSS file, so that is half of the problem solved. I would be quite happy to use this if it were possible to automatically change the query parameter each time gulp runs.

Any thoughts on how this can be achieved, or if it is even possible?

The reasons I would like to do this is I'm constantly developing my app and I use a large sprite sheet which is often rearranged, cache busting is a requirement, and if it could be automatic when gulp runs that would save me a lot of time and effort.


Answer Source

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() + #{')'};


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


.sprite {
    background-image: "url(/build/images/common/sprite.png?v=u95ab40e0)";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download