Skip to content

Instantly share code, notes, and snippets.

@mohsin
Created June 12, 2020 19:00
Show Gist options
  • Save mohsin/c06ddce6ab7aa09f04a62a09981de7a8 to your computer and use it in GitHub Desktop.
Save mohsin/c06ddce6ab7aa09f04a62a09981de7a8 to your computer and use it in GitHub Desktop.
Wix Lazy Image Loading Custom Element
// Add this script as Public/custom-elements/wix-lazy-image.js (yes, create a folder called custom-elements)
// In your Wix page, add the Custom Element, choose Corvid file and select the file which you saved in above step.
// Now set Tag Name as lazy-image and save. Now, press Set Attributes and add a field called src with the correct URL of image.
const addLazyScript = () => {
const script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.2.2/lazysizes.min.js';
script.async = true;
return script;
}
const createImg = () => {
const img = document.createElement('img');
img.className = 'lazyload';
img.style.width = '100%';
img.style.height = '100%';
img.style.position = 'fixed';
return img;
}
class LazyImage extends HTMLElement {
constructor() {
super();
this.img = createImg();
}
connectedCallback() {
this.appendChild(addLazyScript());
this.appendChild(this.img);
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'src') {
this.img.dataset.src = newValue;
}
}
static get observedAttributes() {
return ['src'];
}
}
customElements.define('lazy-image', LazyImage);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment