Skip to content

Instantly share code, notes, and snippets.

@jgarber623
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgarber623/b0fcd7b2a075b3c5231e to your computer and use it in GitHub Desktop.
Save jgarber623/b0fcd7b2a075b3c5231e to your computer and use it in GitHub Desktop.
A derivation of Filament Group's cookie-based critical CSS technique implemented in a Rails app.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>My Great Rails App!</title>
<%- if include_full_css? -%>
<%= stylesheet_link_tag 'application' %>
<%- else %>
<style>
<%= raw assets.find_asset('critical.css') %>
</style>
<noscript>
<%= stylesheet_link_tag 'application' %>
</noscript>
<%- end -%>
</head>
<body>
<!-- My Great Rails App's awesomely semantic markup! -->
<%- if !include_full_css? -%>
<script>
function loadCSS(e){var l=document.createElement('link'),o=document.getElementsByTagName('script')[0],s=document.styleSheets;l.rel='stylesheet';l.href=e;l.media='only x';o.parentNode.insertBefore(l,o);function m(){var d;for(var i=0;i<s.length;i++){if(s[i].href && s[i].href.indexOf(e)>-1){d=true;}}if(d){l.media='all';}else{setTimeout(m);}}m();return l;}
loadCSS('<%= asset_path('application.css') %>');
document.cookie = 'fullCSS=true; expires=<%= (DateTime.now.utc + 7).strftime("%a, %d %b %Y %T GMT") %>; path=/';
</script>
<%- end -%>
</body>
</html>
module ApplicationHelper
def include_full_css?
cookies.has_key?(:fullCSS)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment