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.
JavaScript
x
21
21
1
<head>
2
<script>
3
const viewWidth = window.innerWidth;
4
5
if (viewWidth >= 480) {
6
console.log('big screen');
7
const swiperJS = document.createElement('script');
8
swiperJS.type = "text/javascript";
9
swiperJS.src = "https://cdnjs.cloudflare.com/ajax/libs/Swiper/7.2.0/swiper-bundle.min.js";
10
document.head.appendChild(swiperJS);
11
}
12
</script>
13
</head>
14
15
<body>
16
<script>
17
if (viewWidth >= 480) {
18
const swiper = new Swiper('.swiper');
19
}
20
</script>
21
</body>
Advertisement
Answer
One possible solution I used
swiperJS.addEventListener(‘load’, callback);
to get the call back
JavaScript
1
26
26
1
<head>
2
<script>
3
function loadScript(url, callback) {
4
const viewWidth = window.innerWidth;
5
if (viewWidth >= 480) {
6
console.log('big screen');
7
const swiperJS = document.createElement('script');
8
swiperJS.type = "text/javascript";
9
swiperJS.src = url;
10
swiperJS.addEventListener('load', callback);
11
document.head.appendChild(swiperJS);
12
}
13
}
14
15
function init() {
16
console.log("inside init")
17
const swiper = new Swiper('.swiper');
18
}
19
loadScript("https://cdnjs.cloudflare.com/ajax/libs/Swiper/7.2.0/swiper-bundle.min.js", init)
20
</script>
21
22
</head>
23
24
<body>
25
</body>
26