Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

172
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda