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

128
Visualizações
Conditionally importing JS library

In my Rails 6.x app, I was using Webpacker in order to compile my styles and transpile my JS.

As part of my apps upgrade to Rails 7, I scrapped Webpacker (as it's no longer recommended) and switched over to the new cssbundling-rails and jsbundling-rails gems.

These are super fast and sooo much easier to use.

However, I just ran a Lighthouse report on my site and I think certain pages on my site are loading all my JS even though a lot of it is not even executed on most pages.

For example I have a script that plays audio using the Plyr library on one page.

My script for this, at the top has an import like:

import Plyr from 'plyr'

I've tried to conditionalism this by checking if a specific element exists on the page first before importing but it didn't like that.

How can I only perform some of these imports when they are necessary and not when they are not.

How do I convert the above to be conditional?

Thanks, Neil

UPDATE:

My updated script:

if (document.querySelector('audio')) {
    let audio = document.querySelector('audio');
    import('plyr').then(Plyr => {
        const player = new Plyr(audio, {
            'controls' : ['play'],
            'autoplay' : false
        })
    });
}

The error i'm getting is:

Uncaught (in promise) TypeError: Plyr2 is not a constructor.

How can I access the Plyr object?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Instead of using import Plyr from 'plyr', you can use dynamic import of import('plyr') which you can use anywhere, including conditional logic. Keep in mind, dynamic imports return promises. So async/await So,

if(somevalue === true){
   import('plyr').then(resp => doSomething)
}
about 4 years ago · Juan Pablo Isaza Relatório
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