Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda