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>
Advertisement
Answer
One possible solution I used
swiperJS.addEventListener(‘load’, callback);
to get the call back
<head> <script> function loadScript(url, callback) { const viewWidth = window.innerWidth; if (viewWidth >= 480) { console.log('big screen'); const swiperJS = document.createElement('script'); swiperJS.type = "text/javascript"; swiperJS.src = url; swiperJS.addEventListener('load', callback); document.head.appendChild(swiperJS); } } function init() { console.log("inside init") const swiper = new Swiper('.swiper'); } loadScript("https://cdnjs.cloudflare.com/ajax/libs/Swiper/7.2.0/swiper-bundle.min.js", init) </script> </head> <body> </body>