Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda