Ognjen Regoje bio photo

Ognjen Regoje
But you can call me Oggy


I make things that run on the web (mostly).
More ABOUT me and my PROJECTS.

me@ognjen.io LinkedIn

Overriding rails_amp image helper to cater for lazy-loaded images

#affiliate #amp #rails #technical

I make use of the rails_amp gem in the affiliate site. It generates AMP from normal views.

One of it’s features is automatically converting the image_tag into the AMP compatible alternative.

The affiliate site however has lazy loading that uses jQuery lazy which means that instead of:

<%= image_tag "image.png"%>

it mostly uses:

<%= image_tag "placeholder.png", data: {src: "image.png"}%>

The rails_amp gem then generates the AMP image tag for the placeholder image only.

To solve that the image tag helper rails_amp can be overriden like this:

# config/initializers/image_tag_helper.rb
require 'fastimage'

module RailsAmp
  module ViewHelpers
    module ImageTagHelper
      # override image_tag helper in ActionView::Helpers::AssetTagHelper
      def image_tag(source, options={})
        if controller && RailsAmp.amp_renderable?(controller.controller_path, controller.action_name)
          # check if there is a data[src] attribute
          if options.dig(:data, :src)
            source = options.dig(:data, :src)
          end
          amp_image_tag(source, options)
        else
          super
        end
      end
    end
  end
end

If data[src] is present the source is overriden. Otherwise it functions the same as for regular image tags.