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

Lazy image loading for user provided content #5601

Closed
mmd-osm opened this issue Feb 3, 2025 · 1 comment · Fixed by #5615
Closed

Lazy image loading for user provided content #5601

mmd-osm opened this issue Feb 3, 2025 · 1 comment · Fixed by #5615

Comments

@mmd-osm
Copy link
Contributor

mmd-osm commented Feb 3, 2025

Diary and other user provided content frequently includes rather large external images, which slows down page loading. We could force lazy loading of these assets by adding a loading="lazy" attribute to img tags, as described here: https://developer.mozilla.org/en-US/docs/Web/Performance/Lazy_loading

The change is rather small, but I'm not sure if this doesn't cause unwanted side effects. Does anyone have any opinion on this topic?

diff --git a/config/initializers/sanitize.rb b/config/initializers/sanitize.rb
index c9d6a5dbac..f8f2b784d9 100644
--- a/config/initializers/sanitize.rb
+++ b/config/initializers/sanitize.rb
@@ -2,6 +2,10 @@ Sanitize::Config::OSM = Sanitize::Config.merge(
   Sanitize::Config::RELAXED,
   :elements => Sanitize::Config::RELAXED[:elements] - %w[div style],
   :remove_contents => %w[script style],
+  :attributes => Sanitize::Config.merge(
+    Sanitize::Config::RELAXED[:attributes],
+    "img" => Sanitize::Config::RELAXED[:attributes]["img"] + ["loading"]
+  ),
   :transformers => lambda do |env|
     style = env[:node]["style"] || ""
 
@@ -24,5 +28,7 @@ Sanitize::Config::OSM = Sanitize::Config.merge(
 
       env[:node]["rel"] = rel.split.select { |r| r == "me" }.append("nofollow", "noopener", "noreferrer").sort.join(" ")
     end
+
+    env[:node]["loading"] = "lazy" if env[:node_name] == "img"
   end
 )
@HolgerJeromin
Copy link
Contributor

On a website from me I added this HTML property to all user added images (inline images in a blog like page).
Invisible images (down a few pages) are not loaded till the user scrolls down. The browser is smart enough to fetch them early enough, so even if the image size is not known initially the reflow is not visible.

To summarize: I am pretty sure this will have no downside but will be good with many scenarios.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants