# Injecting jQuery – the right version

**Date:** 2014-02-15  
**Author:** Kees C. Bakker  
**Categories:** jQuery  
**Original:** https://keestalkstech.com/injecting-jquery-the-right-version/

![Injecting jQuery – the right version](https://keestalkstech.com/wp-content/uploads/2014/02/2755481069_30d94b89a5_b.jpg)

---

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.

```js
function loadScript(url, onload) {
    var element = document.createElement('script');
    element.type = 'text/javascript';
    element.src = url;
    element.onload = onload;
    document.getElementsByTagName("head")[0].appendChild(element);
}

function loadJQuery(onload) {

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

        //detect ie8 or less
        if (!document.addEventListener) {
            loadScript('//code.jquery.com/jquery-1.9.1.min.js', onload);
        } 
        else {
            loadScript('//code.jquery.com/jquery-latest.min.js', onload);
        }
    } 
    //jQuery has been loaded - execute onload
    else if (typeof onload !== 'undefined') {
        onload();
    }
}

var onjQueryLoaded = function () {
    alert('jQueryLoaded');
};

loadJQuery(onjQueryLoaded);
```

Scripts are loaded by injecting them into the head. Detecting the *absence* of the `addEventListener` [is an easy way](http://stackoverflow.com/questions/5574842/best-way-to-check-for-ie-less-than-9-in-javascript-without-library/14835682) to sniff out these browsers.

## Bookmarklet bonus

When you're writing a [bookmarklet](http://en.wikipedia.org/wiki/Bookmarklet) you could include the following minified code to load the proper version of jQuery (only 324 characters).

```js
javascript:(function(c){var e=document,a="undefined",b;if(typeof window.jQuery===a){b=e.createElement("script");b.type="text/javascript";b.src="//code.jquery.com/jquery-"+(!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:*/
    alert("jQueryLoaded") 
});
```

Try it.
