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")
});
})();
There are various problems in your code.
querySelector returns one element, and not an array, so document.querySelector("head")[0]makes no sense.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")script element you append.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..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);
})();
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");
}
})();