Skip to content

Instantly share code, notes, and snippets.

@nateberkopec
Last active April 29, 2016 15:07
Show Gist options
  • Save nateberkopec/9760e3a338a09256bfb95658f231a6ee to your computer and use it in GitHub Desktop.
Save nateberkopec/9760e3a338a09256bfb95658f231a6ee to your computer and use it in GitHub Desktop.
class SomeController < ApplicationController
before_action :add_http_preload
private
def add_http_preload
# Always add a Link header to responses to this controller
http_preload script: "application.js", style: "application.css"
http_preload "myfont.woff", as: :font, push: false
# TODO: How should crossorigin work?
# Generated Link headers:
# Link: </assets/application.css>; rel=preload; as=style
# Link: </assets/application.js>; rel=preload; as=script
# Link: </assets/myfont.woff>; rel=preload; as=font; nopush
end
end
@adrianpacala
Copy link

How about:

preload_asset 'application.css', as: :style
preload_asset 'application.js', as: :script

or even:

preload_stylesheet 'application.css'
preload_javascript 'application.js'

@nateberkopec
Copy link
Author

I was thinking we could guess the as bit based on the MIME type/file extension, but that would be impossible to do for object or other similarly universal embeds, so an as: option is probably a great idea. updated.

Full list of things you can push via Link

@nateberkopec
Copy link
Author

Also, since you can push crazy things like workers, iframes, embeds and objects, I don't think preload_asset is a good method name.

In addition, although it adds a preload link, I still like push since it's more descriptive of what we're going to do here (direct the intermediate cache to push responses).

@igrigorik
Copy link

๐Ÿ‘

How about just preload with default option for "push: on" and allow override for "off" (i.e. nopush).

preload 'script.js'
preload 'other/thing', push: false

The above maps cleanly to Preload semantics.

@nateberkopec
Copy link
Author

๐Ÿ‘ definitely would need a push option.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment