Last active
January 21, 2022 17:17
-
-
Save hungmi/fc8a94814a2e6e9013990072e3d291e9 to your computer and use it in GitHub Desktop.
Asynchronously load images with Stimulus.js. Also supports media queries.
This file contains 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
<% # I have a slide contains 6 images. %> | |
<% # And also I have different versions of them based on media queries. %> | |
<% # We can load the 2nd to 6th images asynchronously. %> | |
<% (2..6).each do |num| %> | |
<div data-controller="preload-img" data-preload-img-src-value='<%= asset_path("slides/pc/#{num}.jpg") %>' data-preload-img-media-value="(min-width: 992px)"></div> | |
<div data-controller="preload-img" data-preload-img-src-value='<%= asset_path("slides/mobile/#{num}.jpg") %>' data-preload-img-media-value="(max-width: 991px)"></div> | |
<% end %> |
This file contains 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
import { Controller } from "@hotwired/stimulus" | |
// Connects to data-controller="preload-img" | |
export default class extends Controller { | |
static values = { | |
src: String, | |
media: String | |
} | |
connect() { | |
if (this.hasMediaValue) { | |
if (window.matchMedia(this.mediaValue).matches) { | |
this.preloadImg() | |
} | |
} else { | |
this.preloadImg() | |
} | |
} | |
preloadImg() { | |
let img = document.createElement('img') | |
img.src = this.srcValue | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment