How do I continue executing my .js code after programmatically adding jQuery to the DOM?

How do I continue executing my .js code after programmatically adding jQuery to the DOM?

The 3rd answer in this post shows how to add jquery to the dom but how should you continue executing further code?

For example you can’t just add code underneath the self invoked function because jQuery hasn’t yet loaded. How do I continue writing my .js code so that it executes?

 $(window).on('load', function() {
    // jQuery hasn't yet loaded so can't use this yet.
 });

>Solution :

Execute the code that requires jQuery in the script’s load event listener.

var jQueryScript = document.createElement('script');
jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
jQueryScript.addEventListener("load", function() {
    $(document).ready(function() {
        ...
    });
});
document.head.appendChild(jQueryScript);

Leave a Reply