Thursday, June 25, 2009

Reducing js framework bloat

There are few sites that can achieve a sexy js framework implementation without the assistance of further plugins. Many of my previous jobs required at least the inclusion of a validation plugin for contact form validation and a greybox plugin for viewing image popups.

As you would expect however, the majority of pages won't require all of those additional libraries so you end up with download and initialisation bloat. In small site implementations this can quickly be rectified by implmenting different js includes for different types of templates (although this becomes messy dealing with multiple external initialisation scripts).

On the business school website, there's no way of determining the uses of the page templates and therefore, no way of predetermining what js will be required. On interviewing for the job, I was told there were some 2 thousand pages in the subsite so the varition in usage is too high to try manual control of js. To try making all libraries available for all pages creates a js bloat of over 150kb which is too high. I decided to automate js to dynamically inject libraries if and when they are required.

code to dynamically inject the library if it's not already present:

function includeJs(file) {
var scpt = "";
// Handle multiple include attempts
if($("script[src='" + file + "']").size() == 0) {
scpt = $('').attr('type','text/javascript');
scpt.attr('src',file);
$('head').append(scpt);
}
}

code to call the library when needed:

//find all hyperlinks with .swf in their href
$('a[href*=".swf"]').each(function(e){
includeJs('/js/jquery.flash.js');
//further code
}

0 comments:

Post a Comment