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?
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)
}