0

I'm creating a javascript code using jQuery. But, first, I would like to :

  1. Test if jQuery already exist in the page
  2. Load if not
  3. Load my own jQuery plugin

I've write this small code but I have an error in the start() function :

jQuery is not defined

My code will be in a js file :

 window.addEventListener('DOMContentLoaded', function(){
     
    if (!window.jQuery) {
        loadjQuery(onScriptLoad);
    }else{
        start();
    }
    
 });
 
 function onScriptLoad() {
    console.log('jQuery is load !');
    start();
}

function loadjQuery(callback)
{
    //Get jQuery
   var script = document.createElement('script');
   script.type = "text/javascript";
   script.src = "https://code.jquery.com/jquery-1.12.4.min.js";
   script.integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=";
   script.crossorigin = "anonymous";
   document.getElementsByTagName('head')[0].appendChild(script);
   
   callback();
}

function start(){
    
    (function( $ ) {

        // Plugin definition.
        $.fn.transliveasy = function( options ) {
            debug( this );
            // ...
        };
     
        // Private function for debugging.
        function debug( obj ) {
            if ( window.console && window.console.log ) {
                window.console.log( "Debug : ", obj );
            }
        }
     
     
    })( jQuery );

    console.log('I am load !');         
         
}
Portekoi
  • 1,087
  • 2
  • 22
  • 44
  • 3
    It's because you've inserted the script but it hasn't loaded yet. The browser has only begun to load it when you try to invoke jQuery. Try waiting for the "load" event like in this answer: https://stackoverflow.com/a/43076418/2740650 – user2740650 Oct 05 '20 at 21:25
  • You can try to use `script.onload = callback` but I'm not 100% sure if it work. If it don't I can add answer with delay + setTimeout if you want that always works. – jcubic Oct 07 '20 at 13:59

1 Answers1

0

From @user2740650

It's because you've inserted the script but it hasn't loaded yet. The browser has only begun to load it when you try to invoke jQuery. Try waiting for the "load" event like in this answer: stackoverflow.com/a/43076418/2740650

Portekoi
  • 1,087
  • 2
  • 22
  • 44