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

155
Vistas
Is there any suggestion to add jQuery dynamically with a self executing function?

I want to import jQuery in a JS file dynamically. Here is my code:

(function() {
  var head = document.querySelector("head")[0];
  if (head.classList.contains("En-Script") == true) {
    head.classList.add("En-Script");
    var script = document.createElement("SCRIPT");
    let EnScript = document.querySelector(".En-Script");
    script.type = "text/javascript";
    script.src = "./jquery-3.6.0.min.js";
    EnScript.appendChild("script");
  } else {
    console.log("class_list_added_for_further_process");
  }

  $(document).ready(function() {
    console.log("jquery added successfully")
  });
})();
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

There are various problems in your code.

  • querySelector returns one element, and not an array, so document.querySelector("head")[0]makes no sense.
  • With if (head.classList.contains("En-Script") == true) { you test if head has the class En-Script, which makes no sense in combination with head.classList.add("En-Script")
  • Also adding a class to the head to check if the script is loaded is probably not the best approach, if you want to do that add a class or data attribute to the script element you append.
  • If you already have head why do you use let EnScript = document.querySelector(".En-Script"); to query for it again?
  • EnScript.appendChild("script"); tries to append test string with the content script to EnScript and not the element you created and stored in the script variable.
  • $(document).ready(function() { would not wait for the script to be loaded.
  • Calling .ready( for when you loaded jQuery dynamically also does not make much sense because the DOM is already read.

That's how loading a script could look like:

(function() {
  var head = document.querySelector("head");

  var script = document.createElement("script");
  script.type = "text/javascript";

  script.onload = function() {
    // called when the script is loaded and ready to use
    console.log("jquery added successfully")
  }
  script.src = "https://code.jquery.com/jquery-3.6.0.slim.min.js";

  head.appendChild(script);

})();

about 4 years ago · Juan Pablo Isaza Denunciar

0

There's a few things wrong, you were checking if head had the class "En-Script" and then adding the class to the head, so I changed the validation so it makes sense. Then, you were selecting the head using querySelector which only returns 1 value and using [0] which would work if you were using querySelectorAll instead.

Then you should add the jquery function $(document) after the script has loaded, so I added a script.onload to achieve this.

Also when you append a child you should send the object you created, not a string, so instead of this EnScript.appendChild("script"); I used head.appendChild(script);

(function() {

  var head = document.querySelector("head");
  if (!head.classList.contains("En-Script")) {
    head.classList.add("En-Script");
    var script = document.createElement('script');
    script.type = "text/javascript";
    script.src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js";
    script.onload = function() {
      $(document).ready(function() {
        console.log("jquery added successfully")
      });

    };
    head.appendChild(script);
  } else {
    console.log("class_list_added_for_further_process");
  }


})();

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