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:


Source:

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
scriptList.push("http://code.jquery.com/jquery-1.11.0.min.js");
scriptList.push("https://raw.github.com/gdsmith/jquery.easing/master/jquery.easing.1.1.1.js");
} else {
//load a version of jQuery 2.x
scriptList.push("http://code.jquery.com/jquery-2.0.2.min.js");
scriptList.push("https://raw.github.com/gdsmith/jquery.easing/master/jquery.easing.1.3.js");
}
//custom cross compatible scripts that use
//the same jQuery API that is the same
//on 1.x and 2.x
scriptList.push("./js/myLib.js");
scriptList.push("./js/main.js");
onLoadCallback();

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