Created
March 24, 2022 13:14
-
-
Save ihorduchenko/75afe3ce7de8361b58bb458674627fa0 to your computer and use it in GitHub Desktop.
Load scripts asynchronously and run callback functions (Swiper example)
This file contains hidden or 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
const loadScript = (FILE_URL, async = true, type = 'text/javascript') => { | |
return new Promise((resolve, reject) => { | |
try { | |
const scriptEle = document.createElement('script'); | |
scriptEle.type = type; | |
scriptEle.async = async; | |
scriptEle.src = FILE_URL; | |
scriptEle.addEventListener('load', (ev) => { | |
resolve({ | |
status: true | |
}); | |
}); | |
scriptEle.addEventListener('error', (ev) => { | |
reject({ | |
status: false, | |
message: `Failed to load the script ${FILE_URL}` | |
}); | |
}); | |
document.body.appendChild(scriptEle); | |
} catch (error) { | |
reject(error); | |
} | |
}); | |
}; | |
function initSwipers() { | |
let productItemsImages = document.querySelectorAll('.ProductItem__Swiper'); | |
console.log(productItemsImages); | |
if (productItemsImages) { | |
productItemsImages.forEach(el => { | |
const swiper = new Swiper(el, { | |
}) | |
}) | |
} | |
} | |
if (window.Swiper) { | |
initSwipers(); | |
} else { | |
loadScript('https://unpkg.com/swiper@8/swiper-bundle.min.js') | |
.then( data => { | |
console.log('Swiper loaded successfully', data); | |
initSwipers(); | |
}) | |
.catch( err => { | |
console.error(err); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment