Skip to content

Instantly share code, notes, and snippets.

@egstad
Created May 20, 2019 22:44
Show Gist options
  • Save egstad/fb63462bfa5f196d250613a6c01334ab to your computer and use it in GitHub Desktop.
Save egstad/fb63462bfa5f196d250613a6c01334ab to your computer and use it in GitHub Desktop.
NUXT + Vanilla-lazyload
import LazyLoad from "vanilla-lazyload";
import utils from "./utils";
/* ==========================================================================
LAZYLOAD
==========================================================================
• Once an element enters viewport, load it up!
• Handles lazyloading images, iframes, scripts, etc...
• https://github.com/verlok/lazyload
========================================================================== */
const lazyload = {
loadTimeout: null,
init() {
this.elemsInDoc = document.querySelectorAll(".js-load");
this.elemsInView = [];
// this.bindEvents();
this.options = {
elements_selector: ".js-load",
class_loading: "is-loading",
class_loaded: "is-loaded",
class_error: "is-error",
thresholds: "500px 10%"
}
// initialize
this.instance = new LazyLoad(this.options);
// find images in view
this.getImagesInView();
},
destroy() {
this.instance.destroy();
},
// define images in view
getImagesInView() {
this.elemsInDoc.forEach(el => {
if (utils.isElementVisible(el)) {
// this adds a class before vanilla does
// we use it to index how many are left to load
el.classList.add('is-loading')
this.elemsInView.push(el);
}
});
// if none in view, skip to the end
(this.elemsInView) ? this.inViewDirector() : this.inViewComplete
},
// check if images need more time to load
inViewDirector() {
let toLoad = this.elemsInView.length
this.elemsInView.forEach((el) => {
if (el.classList.contains = "is-loaded") { toLoad-- }
})
// more to load?
if (toLoad > 0) {
this.inViewStart();
}
// all done?
else {
this.inViewComplete();
}
},
// images need more time to load
inViewStart() {
this.loadTimeout = setTimeout(() => {
this.inViewDirector()
}, 200);
},
// all images in view have loaded
inViewComplete() {
window.$app.$store.commit('imagesLoading', false)
if (this.loadTimeout) {
window.clearTimeout(this.loadTimeout);
}
}
}
if (process.client) {
window.onAppReady((app) => {
lazyload.init()
// update on new page
window.$app.$on('route::before', () => {
window.$app.$store.commit('imagesLoading', true)
lazyload.destroy()
})
// update on new page
window.$app.$on('page::mounted', () => {
lazyload.init()
})
})
}
export default lazyload;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment