From c6adf385c5bcb5329e008206e6d59d6d9a470226 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Simonis?= Date: Wed, 23 Oct 2024 14:31:24 +0200 Subject: [PATCH] Add image hook for lazily loading images --- Gemfile | 2 ++ _plugins/lazyloading.rb | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 _plugins/lazyloading.rb diff --git a/Gemfile b/Gemfile index 52e78e8ce8..e460b0e880 100644 --- a/Gemfile +++ b/Gemfile @@ -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 diff --git a/_plugins/lazyloading.rb b/_plugins/lazyloading.rb new file mode 100644 index 0000000000..bb413bc1fe --- /dev/null +++ b/_plugins/lazyloading.rb @@ -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 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