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

127
Views
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 answers
Answer question

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 Report
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!