Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

132
Vistas
Conditionally load and then reference external JS

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>

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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>
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda