i am adding scripts/styles to my dom only when needed. But now, more and more Libraries are switching to be es6-modules and my current technic does not work with these anymore.
I found this, but the answer is rather very old: How does lazy module loading work in ES6
I want to add photoswipe as soon as needed (when a user clicks an image..) Like here: https://photoswipe.com/v5/docs/getting-started/
i tried to change type to "module", did not help
Code:
let src = "/scripts/photoswipe-lightbox.esm.js";
await new Promise(function(resolve, reject) {
let script = document.createElement('script');
script.src = src;
script.type = "module";
script.onload = () => resolve(script);
script.onerror = () => reject("Error");
document.head.append(script);
});
const lightbox = new PhotoSwipeLightbox({...});
lightbox.init();
//PhotoSwipeLightbox is not defined
It successfully adds the script file to the dom, but i cannot instantiate the class. Eg const lightbox = new PhotoSwipeLightbox({...});
I wonder how could i add modules to the dom when needed and use it as expected. My page uses pushState instead of doing full requests, so i have to add those dynamically, plus i dont want to bload my page with unneeded .
Ideas? Thank you in advance