Friday, November 8, 2013

The Code Change That Loaded Our Pages 50% Faster

Yesterday I wrote that I reduced page load times on one of our XPages by 54% by tweaking a little bit of code that was used to display glossary/footnotes in popup dialogs.

I have steeled myself for the inevitable coding advice from the XPage community's obvious jQuery expert, Dr. Marky Roden (who chastised me for pulling a Charles Dickens by not publishing this code yesterday), and am now sharing this code.

You can see the page load times on yesterday's post but what I found was that the original code really started to noticeably increase page load times once the number of elements to be "dialoged" started getting into the hundreds.

When I wrote the code the first time I was in M.A.S.H. mode, which is typical for me, and I figured "...just attach dialogs to all of the elements then call the dialogs when the term is clicked."  I thought a ready-to-go dialog would be faster than one that was on-demand.

After a point it was clear that doing all of that attaching was taking a lot of time so the fix was to do what I thought was not the right thing which was to just run the dialog-attaching code when the element was clicked.  There doesn't appear to be any noticeable downside to the switch and the load time on the page was improved dramatically.

Just an example of how changing code even a little might lead to noticeably improved performance or remove a bottleneck.



ORIGINAL CODE

function updateGlossary() {

      //Attach a jQueryUI Dialog to each element with a class of myDialog

$(".myDialog").dialog({
autoOpen: false,
width:500,
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});

     //Attach a function to the click event of each element with a class of glossaryLink

$( ".glossaryLink" )
.click(function() {
var whichOne="#" + this.id + "Dialog";
$(whichOne).dialog( "open" );
return false;
});

}; //end function



IMPROVED CODE

function updateGlossary() {

     //Attach a function to the click event of each element with a class of glossaryLink
    // but now delay the attaching o' the dialog until the term is actually clicked

$( ".glossaryLink" ).click(function() {

var whichOne="#" + this.id + "Dialog";

$(whichOne).dialog({
autoOpen: false,
width:500,
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});

$(whichOne).dialog( "open" );
return false;
});

}; //end function