Last Updated: February 25, 2016
·
907
· yoannm

Detect and inject jQuery

As a follow up to my Bookmarklet Protip I often needed to check if the page had jQuery, and if not inject it.

So I found a solution for that here and modify it to fill my needs.

Here's mine :

//Check if jQuery is in use.
//Else import it.
(function() {
  var otherlib=false,
      msg='';

  if(typeof jQuery!='undefined' && 
      jQuery !== null) {
    msg='This page already using jQuery v'+jQuery.fn.jquery;
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("jquery:loaded",true,true);
      evt.msg = msg;
    document.dispatchEvent(evt);
  } else if (typeof $=='function') {
    otherlib=true;
  }
  function getScript(url,success){
    var script=document.createElement('script'),
      head=document.getElementsByTagName('head')[0],
      done=false;
    script.src=url;
    script.onload=script.onreadystatechange = function(){
      if ( !done && 
              (!this.readyState || 
              this.readyState == 'loaded' || 
              this.readyState == 'complete') 
          ) {
        done=true;
        if(success !== undefined && 
           typeof success === "function") 
                 success();
        script.onload = script.onreadystatechange = null;
        head.removeChild(script);
      }
    };
    head.appendChild(script);
  }

  getScript('http://code.jquery.com/jquery-latest.min.js',function() {

    var evt = document.createEvent("HTMLEvents");
    if (typeof jQuery=='undefined') {
      msg='Sorry, but jQuery wasn\'t able to load';
      evt.initEvent("jquery:error",true,true);
      evt.msg = msg;
      document.dispatchEvent(evt);
    } else {
      msg='This page is now jQuerified with v' + jQuery.fn.jquery;
      if (otherlib) {msg+=' and noConflict(). Use $jq(), not $().';}
      evt.initEvent("jquery:loaded",true,true);
      evt.msg = msg;
      document.dispatchEvent(evt);
    }
  });
})();

Basically, it checks if the page is running jQuery, and if not, get the latest one from jquery's cdn.

It's firing an event when loaded : "jquery:loaded".

Hope it's useful. Share if you can get it better.
It may need a poly-fill for the event firing.