How to load Javascript dependencies dynamically

Loading jQuery using plain Javascript::

// inject e.g. jQuery into a webpage
var thescript =  'http://code.jquery.com/jquery-latest.min.js';
var newscript = document.createElement( 'script' );
newscript.setAttribute( 'src', thescript );
newscript.setAttribute( 'type', 'text/javascript' );
var head = document.getElementsByTagName("head")[0];
head.appendChild(newscript);

To call this from your script with a test to see if jQuery is loaded:

// Test if jQuery is loaded 
if( typeof(jQuery) == 'undefined') 
{
  // code from previous listing
}

Leave a Reply