Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
Lazy Load / Add when needed ES6 Modules (eg Lightbox)

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

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!