Dynamically requiring images?

I've a module that contains a class that represents the Hero section of my site. The Hero has a slider of images. At the top of the class I'm importing the images:
const servers = require('...');
const solar = require('...');
const datacenter = require('...');
const servers = require('...');
const solar = require('...');
const datacenter = require('...');
Snippet of the string of html produced to insert into the DOM:
<div class="image-wrapper">
<img class="hero__image" src=${servers} alt="">
<img class="hero__image" src=${solar} alt="">
<img class="hero__image" src=${datacenter} alt="">
</div>
<div class="image-wrapper">
<img class="hero__image" src=${servers} alt="">
<img class="hero__image" src=${solar} alt="">
<img class="hero__image" src=${datacenter} alt="">
</div>
Nothing special. But now I'd like to wait until the page is fully loaded before requiring the solar and datacenter images. So in the class I add a function to set up the lazy loading:
_initLazyLoading() {
window.addEventListener('load', () => {
this.solar = require('...');
this.datacenter = require('...');
});
}
_initLazyLoading() {
window.addEventListener('load', () => {
this.solar = require('...');
this.datacenter = require('...');
});
}
But I assume this isn't working because I can't simply expect the already rendered html to update the src of the img? Not entirely sure how to approach this - especially if I then look to use a <picture> element with different sources 🤔 EDIT So the solution was to dynamically require the image in the <img> src attribute, and insert the html on load instead. I guess that also gives me some options RE the <picture> tag
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server