1

I have some JS, CSS, image files on my page and I'm using cache so when I revisit my page browser doesn't hit my server.

But when I refresh my page, browser hit the server and my server returns 304 NOT MODIFIED.

I know it's usual phenomenon but I wanna know if there is any method to prevent browser from hitting my server and just load those from the cache instead when user refresh the page.

For example when I refresh google page some of their resources are loaded from cache not 304 NOT MODIFIED.

Can anybody help web newbie :) ?

F__M
  • 1,518
  • 1
  • 19
  • 34
  • After this, the only way to force a user to load newer js and css files from your server would be to change the names or add query params. Sending a response header of 304 isn't that heavy on the server. – Anirudh Ramanathan Jun 02 '13 at 12:54
  • possible duplicate of [Website image caching with Apache](http://stackoverflow.com/questions/447014/website-image-caching-with-apache) – CBroe Jun 02 '13 at 14:50

1 Answers1

0

This is normal behavior and ordinarily I'd just live with it. As long as you've set the expiration or max-age settings properly then the 304 messages will only happen upon refresh, as you say. And as long as your users aren't hitting refresh regularly, then the 304 will not typically occur as people browse the site.

However, there are some situations in which you can prevent the 304 message even when the user refreshed the page.

  1. Setting the background-image of an element through Javascript.
  2. Using an iframe to pull content that has a max-age (note that they can still refresh the iframe by right-clicking inside it and clicking refresh).

Here's a background-image example if you want to try it out...

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="example-image" style="height: 250px;"></div>
<script type="text/javascript">
    $("#example-image").css("background", "white url(/images/myImage.jpg) no-repeat");
</script>

UPDATE

I was thinking AJAX GETs would work but it appears I was wrong so I've removed that from the list. In any case, the solutions I've listed above do work but they are clunky and unpleasant which is why I normally don't bother with this.


UPDATE #2

Steve Souders has some interesting experiments regarding this issue... http://www.stevesouders.com/blog/2013/02/26/reloading-post-onload-resources/

Steve Wortham
  • 21,740
  • 5
  • 68
  • 90
  • Thanks a lot for your reply :) But setting background image with javascript doesn't seems to work, I mean still get 304 – Eclipse Kim Jun 03 '13 at 02:28
  • @EclipseKim - I just tried it again and it seems to be working about 50% of the time in IE10. If you use the `setTimeout` function with 100 ms or so (as Steve Souders did), then it'll work just about every time in IE10 and Chrome. – Steve Wortham Jun 03 '13 at 04:33