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;
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 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="//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")
});