Loading a different JavaScript library based on the browser.

This article could be used for any libraries, but we are going to talk about a specific case study using jQuery as an example. First you should know that this is frowned upon in the development community and you should use modernizer.js to do feature detections to solve individual problems. Never the less we are going to go into how to do this shrewd practice.

JQuery has moved from 1.x to 2.x. The 1.x library supports IE6 to IE8. At the time of the writing of this article IE8 represents less than 4 percent of the market. But some of you might want to upgrade your jQuery library to 2.x while keeping the old support for IE8. After all you spent all that time making your site compatible with IE8 all those years ago. So you will need to load jQuery 2.x when it is IE9+ and jQuery 1.x when it is less than or equal to IE8.

First in we need to detect if we are using IE8 or less using IE browser sniffing:

We initialize the isIE8OrLess variable to false in the script tag ID 'set-ie-var'. Then if the user agent browser is IE8 or less the script tag 'init-ie-var' will set isIE8OrLess to true. At the bottom of the code snippet above there is the script tag with the ID 'use-ie-var' which is where we will create our JavaScript loader code. But first we need some code to do the loading of the external JavaScripts.

Lets use this code snippet for loading external JavaScript files:


The above snippet can be put in the script tag with the ID 'set-ie-var' we will use the function loadScript later on in the script tag with the ID 'use-ie-var' at the bottom of the body tag.

Now we need to edit the script at the bottom of the body tag with the ID 'use-ie-var' to load each library and its dependancies:

var scriptList = new Array();
var onLoadCallback = function(){
//load the next script if there are any
if (scriptList.length){
loadScript(scriptList.shift(), onLoadCallback);
if (isIE8OrLess){
//load a version of jQuery 1.x
} else {
//load a version of jQuery 2.x
//custom cross compatible scripts that use
//the same jQuery API that is the same
//on 1.x and 2.x

This method could be used to load dojo code or any other library that may have undergone a similar upgrade. Plus it is a very simple way to load code and its dependancies without using some feature loaded library like RequiresJS.

comments powered by Disqus