Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
Cargue condicionalmente y luego haga referencia a JS externo

Me gustaría cargar un script JS externo basado en una condición (el ancho de la pantalla del usuario), luego ejecutar un script que haga referencia a ese JS externo.

Quiero cargar el JS externo lo antes posible, así que lo agregué a <head> , pero cuando hago referencia al JS más adelante en <body> , se muestra como undefined .

Supongo que esto se debe a la carga síncrona de JS, pero no sé cómo hacerlo funcionar.

 <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 answers
Answer question

0

Una posible solución que utilicé

swiperJS.addEventListener('cargar', devolución de llamada);

para recuperar la llamada

 <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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!