Add the following line to your ApplicationController
:
around_action AssetPreloadingBag::Filter
And when you want to prerender something, you can simply call:
AssetPreloadingBag::Asset.as_fetch('/my-resource') # for instance
This works quite well with ViewComponent, imagine the following IconComponent
which lazy loads SVG images as inline SVGs:
class IconComponent < ViewComponent::Base
def initialize(name)
@path = asset_pack_url("media/images/#{name}.svg")
end
def before_render
AssetPreloadingBag::Asset.as_fetch(@path).register!
end
end
<my-app-icon path="<%= @path %>"></my-app-icon>
Now instead of having a waterfall of requests, we tell the browser all your assets, or even better - inform our CDN to send these assets using HTTP/2 push.