Skip to content

Instantly share code, notes, and snippets.

@kgrz
Last active March 16, 2024 15:34
Show Gist options
  • Save kgrz/ef28e9beae4c50dc2443 to your computer and use it in GitHub Desktop.
Save kgrz/ef28e9beae4c50dc2443 to your computer and use it in GitHub Desktop.
Jekyll Plugin to embed CSS inline in a HTML file. Useful for embedding Above the Fold CSS content if it's in a different file.
# Usage:
# This adds a tag by the name `inline_css`. It takes one argument which is the
# path to a CSS file without any quotes:
#
# {% inline_css public/css/atf.css %}
#
# This would then read the file in the given directory relative to the root of
# the Jekyll installation and then embed that CSS at that location.
#
# Installation:
#
# Copy this file and place it under _plugins directory. Naming of the file
# doesn't matter
module Jekyll
class InlineCssTag < Liquid::Tag
def initialize(tag_name, path_to_atf_css, tokens)
super
full_path_to_atf_css = File.expand_path(path_to_atf_css.gsub("\"", '').strip)
@atf_css_raw = File.read(full_path_to_atf_css)
end
def render(context)
source = '<style type="text/css" media="screen">'
source += @atf_css_raw
source += '</style>'
end
end
end
Liquid::Template.register_tag('inline_css', Jekyll::InlineCssTag)
@TomPham97
Copy link

Thank you for the plugin, and is there a way to deliver critical JS/CSS inline and deferr all non-critical JS/styles to speed up loading? My page is loading very slowly on mobile and Google Pagespeed suggests removing render-blocking resources.

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