2

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);
}
0

1 Answer 1

7

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";
Sign up to request clarification or add additional context in comments.

5 Comments

Ya because once document is parsed, appending script would load it asynchronously
It certainly won't have even started the executing the jQuery code until the function that added it to the DOM has finished running. JavaScript is single threaded.
@Quentin What do you mean? I'm not sure to understand it.
@A.Wolff previously i type onLoad which should be onload. Quentin was pointing this.
@void Ya but i'm talking about his first comment here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.