Last active
October 19, 2022 21:40
-
-
Save jess/9497c3fa12aac00aa0659dbb8f6d9157 to your computer and use it in GitHub Desktop.
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
## js at bottom of layout | |
# source https://www.npmjs.com/package/vanilla-lazyload | |
<script> | |
(function(w, d){ | |
var b = d.getElementsByTagName('body')[0]; | |
var s = d.createElement("script"); | |
var v = !("IntersectionObserver" in w) ? "8.17.0" : "10.19.0"; | |
s.async = true; // This includes the script as async. See the "recipes" section for more information about async loading of LazyLoad. | |
s.src = "https://cdn.jsdelivr.net/npm/vanilla-lazyload@" + v + "/dist/lazyload.min.js"; | |
w.lazyLoadOptions = {/* Your options here */}; | |
b.appendChild(s); | |
}(window, document)); | |
</script> | |
# create a helper | |
def lazy_image_tag(src, args = {}) | |
css_class = args.delete(:class) | |
args[:class] = [css_class, "lazy"].reject(&:blank?).join(" ") | |
data = {} | |
orig_data = args.delete(:data) | |
data.merge! orig_data if orig_data.present? | |
data.merge! src: asset_path(src) | |
args[:data] = data | |
tag("img", args) | |
end | |
# usage | |
# take any image_tag and prepend lazy_ | |
<%= lazy_image_tag "bios/jess.jpg", width: "350", height: "228", alt: "Jess Brown - Rails Dev", data: {some_attr: "xxx"} %> | |
# output | |
<img width="350" height="228" alt="Jess Brown - Rails Dev" class="lazy" data-some-attr="xxx" data-src="/bios/jess.jpg" /> | |
# processed (when img comes into viewport) | |
<img width="350" height="228" alt="Jess Brown - Rails Dev" class="lazy error" data-some-attr="xxx" data-src="/bios/jess.jpg" src="/bios/jess.jpg" data-was-processed="true"> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment