Last active
July 12, 2025 18:19
-
-
Save taoky/8835a3f8eee01d0e8b569d46237388f3 to your computer and use it in GitHub Desktop.
jekyll keep image aspect-ratio to avoid CLS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Initially generated by LLM | |
# Put in _plugins/ and add fastimage and nokogiri to deps | |
require 'fastimage' | |
require 'nokogiri' | |
Jekyll::Hooks.register %i[pages posts], :post_render do |page| | |
next unless page.output_ext == '.html' | |
doc = Nokogiri::HTML5.parse(page.output) | |
changed = false | |
doc.css('img:not([height])').each do |img| | |
src = img['src'] | |
next if src.nil? || src =~ %r{^https?://} | |
path = File.join(page.site.source, src) | |
next unless File.exist?(path) | |
w, h = FastImage.size(path) | |
next unless w && h | |
img['style'] = [img['style'], "aspect-ratio:#{w}/#{h};"].compact.join | |
changed = true | |
end | |
page.output = doc.to_html if changed | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment