Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add image hook for lazily loading images #464

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ end
gem "nokogiri"
gem "open-uri"

gem "fastimage"

# Maybe in the future
# https://rubygems.org/gems/jekyll-scholar
# https://rubygems.org/gems/jekyll-assets
Expand Down
32 changes: 32 additions & 0 deletions _plugins/lazyloading.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# _plugins/image_aspect_ratio_hook.rb
require 'nokogiri'
require 'fastimage'

Jekyll::Hooks.register :pages, :post_render do |doc|
# Process only HTML output from markdown
next unless doc.output_ext == ".html"

# Parse the document's HTML output using Nokogiri
doc_html = Nokogiri::HTML(doc.output)

# Find all <img> tags in the HTML
doc_html.css('img').each do |img|
# Get the image's src attribute
img_src = img['src']

# Check if the image exists and can be processed
if File.exist?(img_src)
# Get the image dimensions using FastImage
width, height = FastImage.size(img_src)
next unless width && height

gcd = width.gcd(height)
# Add a style attribute to the img tag with the aspect ratio
img['style'] = "#{img['style']} aspect-ratio: #{width / gcd} / #{height / gcd};"
img['loading'] = "lazy"
end
end

# Save the modified HTML back to the document
doc.output = doc_html.to_html
end
Loading