Skip to content

Instantly share code, notes, and snippets.

@appelgran
Created December 10, 2021 12:52
Show Gist options
  • Save appelgran/45ccf1298cf7bf9b8d85d1d8783daf2a to your computer and use it in GitHub Desktop.
Save appelgran/45ccf1298cf7bf9b8d85d1d8783daf2a to your computer and use it in GitHub Desktop.
Swiper loading optimization
/*
* Include this file early and then initialize your Swipers using
* swiperLazyInit(...). Swiper lib can then be loaded async or later.
*
* Re-configure example: var slideshow = new Swiper("#slideshow", { speed: 400 });
* Becomes: swiperLazyInit("#slideshow", { speed: 400 }, function(slideshow) { });
*/
function swiperLazyInit(swiperContainer, parameters, callback) {
if (window.Swiper) {
// fix with init to break up the creation and initialization of the swiper in two parts
// allowing execution of other javascript in between
if (!parameters) {
parameters = {};
}
var initBreakMode = false;
if (parameters.init === undefined || parameters.init === true) {
parameters.init = false;
parameters.preloadImages = false;
initBreakMode = true;
}
// create
console.time("Creating Swiper " + swiperContainer.toString());
var swiper = new Swiper(swiperContainer, parameters);
console.timeEnd("Creating Swiper " + swiperContainer.toString());
if (initBreakMode) {
setTimeout(function () {
console.time("Initing Swiper " + swiperContainer.toString());
swiper.init();
//setTimeout(function () { swiper.preloadImages(); }, 0);
console.timeEnd("Initing Swiper " + swiperContainer.toString());
if (callback) {
callback(swiper);
}
}, 0);
}
else if (callback) {
callback(swiper);
}
}
else {
setTimeout(function () { swiperLazyInit(swiperContainer, parameters, callback); }, 50);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment