0

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.
 });
user1532669
  • 2,288
  • 4
  • 36
  • 72
  • Use a Promise - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise Inside the body of your Promise add the code that injects jQuery and everything else can be in the then() method for any code that relies on jQuery. – Tom Hanks Jan 25 '23 at 23:17
  • I think you can add a `load` event listener to the `script` element that you add, and run the code there. – Barmar Jan 25 '23 at 23:17
  • @TomHanks How do you make the promise wait for jQuery to be loaded? – Barmar Jan 25 '23 at 23:18
  • @barmer at the end of the function that injects jquery into the DOM. – Tom Hanks Jan 25 '23 at 23:19
  • 1
    @TomHanks But jQuery is loaded asynchronously, that's the problem. – Barmar Jan 25 '23 at 23:20

1 Answers1

1

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);
Barmar
  • 741,623
  • 53
  • 500
  • 612