Ignore cache in preprocess function I have a content type 'homepage' containing one node which is used a the homepage. This node has a multivalue image field, and I need to randomly select one of those images to show on the homepage on every site visit. I have written the logic for this in the THEME_preprocess_node function in my THEME.theme file. This is working fine, but the site in question is still in development mode with most caching deactivated. I'm worried that once the site goes live and the caching is activated, it will serve the homepage from cache and therefore always show the same image until the cached version of the page expires.

Is that the case, or are the preprocess functions evaluated on every page visit even when the cache is active? If not, how can I circumvent this to get a random image every time?

This is the code I have written for this: 

  $imgages = $node-&gt;get('field_frontpage_header_image');
  $random = $imgs-&gt;get(rand(0, $imgages-&gt;count() - 1))-&gt;getValue();
  $img = File::load($random['target_id']);
  $variables['random_header_image'] = ImageStyle::load('frontpage_header')-&gt;buildUrl($img-&gt;getFileUri());


I then use {{ random_header_image }} in the twig template. Maybe I can change this variable to a render array with a cache setting of max-age =&gt; 0? Not sure if this works in preprocess functions though ...

Thanks!
If it's a limited set of pictures that you have then I would just write a custom formatter that displays for example an image tag with a data attribute that has your list of image paths (maybe with the first image already set as non-JS fallback maybe). then you just need small bit of JS that picks one of those randomly and sets it as the actual src attribute. Your page is fully cacheable then and while it might still be a noticeable delay until the image shows up, that can even happen with static image links on slower connections. 

And it will certainly be much faster than an ajax request.

The placeholder approach might also work and Drupal supports that kind of out of the box with dynamic page cache, doesn't need a reverse proxy or so for that. but you would have to disable the internal page cache then on that page. See http://www.qed42.com/blog/lazy-builders-drupal8 for an example on that. 

The way that works with Dynamic Page cache is that the whole page with the placeholders is cached, and then calls the defined lazy builders which returns the actual content for the current request. You would want to use a similar approach as with JS, prepare all image urls for example already as arguments and then just pick one from that array and render it.