开发者

Cache Busting images inside CSS

My situation

I am currently using Cache Busting when I include CSS files like this:

echo "<link href='stylesheet.css?" . filemtime('stylesheet.css') . "' />"

My goal

Now I would like to do something similar for the images I am including inside my CSS file.

The problem

The problem is that I cannot use PHP inside my CSS files and I would rather keep my CSS files seperated.

My question

How can I add the filemtime() to the images inside my CSS files while keeping the files seperated?

Edit

I would like to use Far开发者_如何转开发 Future Expires headers to cache the files.


You could actually rename your css files as style.css.php and then use PHP inside them. As long as the post-processing result is in the proper CSS format, it should work. I've done it in the past. I'm not sure if it's necessary, but if that gives you problems, you can use a header('Content-type...') kind of thing and ensure it's sent as a CSS file.


To achieve cache-busting, the best way is to send the proper headers. Make sure Apache is configured to send a Expires: now header. So in a .htaccss file:

Header always set Cache-Control "no-store, no-cache, must-revalidate"
Header always set Expires "Thu, 01 Jan 1970 00:00:00 GMT"

That will always force no-caching of all content in its directory and any under.

However, if you wanted to conditionally cache, what I would suggest, is doing one of a few things.

  1. Include a version number in the name of the CSS file. So you'd have a file that looks like mycss.1.css, mycss.2.css. This takes a little more work since you need to coordinate both filenames. But it's better since you aren't sending the files with PHP (no resource hit), you can use a CDN (even better) and you can still take advantage of far-future expires headers.

  2. Set the Cache-Control: must-revalidate header and a proper E-Tag header so that all it needs to do is send a 304 Not Modified header if the content didn't change...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜