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

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

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 Relatório

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 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