Search code examples
imageruby-on-rails-3.1preload

Rails 3.1: How to preload images


With Rails 2.x, you could "preload" all images (be it the HTML tag or the CSS background image) by simply including them somewhere in your home page, by using something like:

<image src="whatever_image.png" width="1" height="1" border="0">

In Rails 3.x, this still works for preloading CSS background images, but apparently not for the HTML image tag. Probably because the source code shows a changed image file name, along the lines of:

<img src="/assets/whatever_image-9935e606c9acc98936269b2dc192167f.png" />

So how would you have to change your preloading tactic with Rails 3.x?


Solution

  • The best practice now is to use the <link> tag to define images to preload. You can use the Rails URL helper to ensure you're specifying the exact same URL in your generated CSS.

    For example, add this in the <head> section:

        <link rel="preload" href="<%= image_url("layout/bg-texture-pattern.webp") %>" as="image" type="image/webp">
    

    Make sure you test and inspect the browser network requests to see that it's only requested once, and before other images. I was able to see the difference inspecting before/after.

    The other attributes help ensure the browser can optimise it as much as possible. Refer: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel/preload