Injecting jQuery – the right version

Sometimes you'll need to inject jQuery into a page that has already been loaded. I like to work on the latest version of jQuery, but since IE8 and lower aren't supported anymore, we'll need to implement a fallback to version 1.9.1.

function loadScript(url, onload) {
    var element = document.createElement('script');
    element.type = 'text/javascript';
    element.src = url;
    element.onload = onload;

function loadJQuery(onload) {

    //detect jquery
    if (typeof window.jQuery === 'undefined') {

        //detect ie8 or less
        if (!document.addEventListener) {
            loadScript('//', onload);
        else {
            loadScript('//', onload);
    //jQuery has been loaded - execute onload
    else if (typeof onload !== 'undefined') {

var onjQueryLoaded = function () {


Scripts are loaded by injecting them into the head. Detecting the absence of the addEventListener is an easy way to sniff out these browsers.

Bookmarklet bonus

When you're writing a bookmarklet you could include the following minified code to load the proper version of jQuery (only 324 characters).

javascript:(function(c){var e=document,a="undefined",b;if(typeof window.jQuery===a){b=e.createElement("script");b.type="text/javascript";b.src="//"+(!e.addEventListener?"1.9.1":"latest")+".min.js";b.onload=c;e.getElementsByTagName("head")[0].appendChild(b)}else{if(typeof c!==a){c()}}})(function(){
    /*add your code here:*/

Try it.