Use jQuery without Script tag in head

Viewed 211

So I want to make jQuery load inside my script. the user doesn't have to add the <script> to the head, but the script adds automatically. I tried using:

(function() {;
    var script = document.createElement("SCRIPT");
    script.src = '/src/jquery-embed.js';
    script.type = 'text/javascript';
    document.getElementsByTagName("head")[0].appendChild(script);
    var checkReady = function(callback) {
      if (window.jQuery) {
        callback(jQuery);
      } else {
        window.setTimeout(function() {
          checkReady(callback);
        }, 20);
      }
    };
    checkReady(function($) {
          //code here
          fucntion callbutton {
            console.log("i return as not defined when called by a button")
          }

when I add it, it works fine but all my functions break. How can I go about this without screwing up more?

edit: Link to the file im working on here

2 Answers

Per discussion, to achieve your goal you must ask your clients to delay their script execution until you've loaded your libraries (jQuery in this case).

Shown below is all that is necessary to accomplish the loading:

var script = document.createElement('SCRIPT');
document.getElementsByTagName('head')[0].appendChild(script);
script.src = 'https://code.jquery.com/jquery-3.5.1.min.js';
script.onload = () => {
  document.dispatchEvent(new CustomEvent('doYourThing'));
};

Then, your users would use this code:

    document.addEventListener('doYourThing', ()=>{
    // End user code that relies on jQuery goes here
    });

Here is a plunkr that demonstrates the principle.

You forgot document.body.appendChild() and you also forgot to add the parentheses after callbutton change it to this:

(function() {
    var script = document.createElement("SCRIPT");
    document.body.appendChild(script);
    script.src = '/src/jquery-embed.js';
    script.type = 'text/javascript';
    document.getElementsByTagName("head")[0].appendChild(script);
    var checkReady = function(callback) {
      if (window.jQuery) {
        callback(jQuery);
      } else {
        window.setTimeout(function() {
          checkReady(callback);
        }, 20);
      }
    };
    checkReady(function($) {
          //code here
          function callbutton(){
            console.log("i return as not defined when called by a button")
          }
    }
  })
Related