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

129
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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