Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Samuel Shackelford
Samuel Shackelford
1,213 Points

Clearing cache on BACKGROUND images in CSS?

I was having the same problem as many others with the placeimg.com images being cached. Tried multiple things and found the javascript option as below worked best.

<script> document.querySelector("img").src += "?nocache=" +Math.random();</script>

Wondering if you can do the same thing with the background image in the CSS? I've tried using the same script in the CSS and it doesn't seem to work. Is there a way to load a random image from placeimg.com as the background?

3 Answers

Cory Harkins
Cory Harkins
16,500 Points

Hi Samuel!

If I am reading you correctly, you just want a JS solution to adding a placeholder image in the CSS rule for background-image?

The code you provided:

<script> document.querySelector("img").src += "?nocache=" +Math.random();</script>

Translated into background image:

<script> 
    var imageDiv = document.getElementById("randomImg");
    var height = 480;
    var width  = 640
    imageDiv.style.backgroundImage =  `url("http://placeimg.com/${height}/${width}/any?nocache=${Math.random()}")`;
</script>
Steven Parker
Steven Parker
231,008 Points

Yes, you can do the same thing but you have to replace the "style.backgroundImage" setting with a complete url instead of just appending the "src" attribute of an image. For example, to give the "header" a 400px background:

document.querySelector("header").style.backgroundImage =
    `url("//placeimg.com/400/400/any?nocache=${Math.random()}")`;
Samuel Shackelford
Samuel Shackelford
1,213 Points

Sorry, I should have been more specific. The background image I'm referring to is the header background. Will that still work?

header { text-align: center; background: url('http://placeimg.com/400/400/any') no-repeat top center ; background-size: cover; overflow: hidden; padding-top: 60px;

Steven Parker
Steven Parker
231,008 Points

Sure, I revised the example in my answer.

Cory Harkins
Cory Harkins
16,500 Points

Same principle applies, target the dom element, then set the background image via element.style.backgroundImage = string of url