I'd like to load an external JS script based on a condition (the user's screen width), then execute a script which references that external JS.
I want to load the external JS as early as possible, so I've added it to the <head>, but when referencing the JS later in the <body>, it shows as undefined.
I assume this is due to the synchronous loading of JS but can't figure how to make it work.
<head>
<script>
const viewWidth = window.innerWidth;
if (viewWidth >= 480) {
console.log('big screen');
const swiperJS = document.createElement('script');
swiperJS.type = "text/javascript";
swiperJS.src = "https://cdnjs.cloudflare.com/ajax/libs/Swiper/7.2.0/swiper-bundle.min.js";
document.head.appendChild(swiperJS);
}
</script>
</head>
<body>
<script>
if (viewWidth >= 480) {
const swiper = new Swiper('.swiper');
}
</script>
</body>