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.
 });
5
  • Use a Promise - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 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. Commented Jan 25, 2023 at 23:17
  • I think you can add a load event listener to the script element that you add, and run the code there. Commented Jan 25, 2023 at 23:17
  • @TomHanks How do you make the promise wait for jQuery to be loaded? Commented Jan 25, 2023 at 23:18
  • @barmer at the end of the function that injects jquery into the DOM. Commented Jan 25, 2023 at 23:19
  • 1
    @TomHanks But jQuery is loaded asynchronously, that's the problem. Commented Jan 25, 2023 at 23:20

1 Answer 1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.