I am dynamically adding <script> tags for different .js resources into the head, however I receive an error exclaiming that jQuery is not defined.
I know that jQuery is in fact working, as other functions further down the flow are working correctly. Below is the code that I am using to dynamically add these scripts to the header. As you can see, I also include jQuery before any other plugins.
document.addEventListener("DOMContentLoaded", AddExternals)
function AddExternals(){
var jq = document.createElement("script");
jq.type = "text/javascript";
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js";
var t2e = document.createElement("script");
t2e.type = "text/javascript";
t2e.src = "/test/rfsystem/rfJavascript/table2excel.js";
document.getElementsByTagName("head")[0].appendChild(jq);
document.getElementsByTagName("head")[0].appendChild(t2e);
console.log(jQuery);
}
1 Answer 1
Just after appending the script tag you can not expect that the script has been pulled over from the network and is embedded on to your page. It will load asynchronously.
You need to wait, or you can use .onload on that script.
Ex: You should also append the script to the DOM before attaching the onload event and You should set the src attribute after the onload event:
var jq = document.createElement("script");
jq.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(jq);
jq.onload = function() { console.log(jQuery); };
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js";
5 Comments
onLoad which should be onload. Quentin was pointing this.