Set no browser cache in drupal

I’ve recently been adding cache to a clients website for admins. It’s been quite the learning process and today I think I’ve finally nailed the final bug.

On a set of pages we’re using a module to order displayed videos called Draggable Views. We noticed that anonymous users would sometimes, but not all the time, see an old sort order after the videos were reordered.

After much fussing around, refreshing and checking of drupal core and views caching I noticed that anonymous users would only see the old page if the cursor was put in the address bar and the return key hit. However if the refresh button or command/ctrl + r was used the correct order would be seen.

And then by looking at the network tab in dev tools I noticed that it was, of course, browser caching which was the final layer I’d missed.

How to fix this?

Drupal has a function called drupal_add_http_header() which allows setting or replacing of header values.
Great, where shall this go?
Well, I put it in template.php and it worked.
Here’s the line to make browsers call the page on each load; drupal_add_http_header('Cache-Control', 'no-cache, must-revalidate, post-check=0, pre-check=0')

Now, it seems like this only requested the html, and since subsequent loads had the same CSS, JS and images, those were not requested by the browser. So it didn’t force no cache for those items. Cool beans (in this case)!

I also didn’t want this to happen on all pages so I added a check of the url to filter it down to only the paths I wanted.

//set no browser cache for specific paths
if(strpos($_SERVER['REQUEST_URI'], 'node') !== false){
  drupal_add_http_header('Cache-Control', 'no-cache, must-revalidate, post-check=0, pre-check=0');
}

Leave a Reply

Your email address will not be published. Required fields are marked *