Optimised jQuery Corners plugin

Thursday, 19 July 2007

I’ve created an optimised version of Dave Methvin’s excellent jQuery corner plugin. This allows jQuery users to apply all sorts of fancy effects to the corners of web page elements: the now-standard Web 2.0 rounded corners, bevels, dog-ears and many more. The plugin works by injecting extra elements into the page, and I noticed a way to achieve the same effect with fewer elements. This improves the speed and memory usage of the plugin.

The exact effect depends on the web browser and on the specific effects being used — on the jQuery Corner Demo site, the optimised version creates 35% fewer page elements and runs about 15% faster.

I will send my modifications to Dave soon I have sent my modifications to Dave, so they may one day find their way into the official jQuery Corners plugin. But till then, you can get the optimised version here.

Download

Note: My modification is based on an older version of the corners plugin, which is not compatible with Internet Explorer 8. For this reason I do not recommend using my modified plugin as-is. Either I or Dave will one day port the optimised code to the latest corners plugin. Until then, you should just stick with the official plugin.

Here is jquery.corner.js. Just replace the original version with it, and be blown away by the moderate speedup.

How it works

The original plugin works by adding a whole bunch of 1-pixel height divs (“strips”) to the top and bottom or the affected element. The body of each div is transparent, and it has left and right borders that are the same colour as the background colour of the parent element. The effect is that the corners of the element are covered up by a rounded pattern of borders, making it look as if it has rounded corners. Here’s a larger-than-life picture of the top of a rounded element, where the rounding is done by the 8 single strips with varying border widths at the top.

Original corner

My optimisation is simple: adjacent strips that have the same borders are combined, as follows.

Optimised corner

For rounded corners, this creates about 30% fewer strips (5 instead of 8 in this case). This uses less memory and also saves rendering time. For other corner styles, the savings may be more or less.

The code I have added is a bit more verbose than the original code — I have used longer variable names and added a couple of comments. The modified code has worked for me everywhere I have tried it but I have not done exhaustive testing.

Overall, you probably won’t notice much improvement unless you use a lot of rounded corners. On this website, using the optimised plugin saved around 100ms depending on the page and browser; on a preliminary design of this website that used hundreds of rounded corners, the optimisation saved several seconds.

Tags: , ,

21 comments

You can leave a comment, or trackback from your own site.

Leave a comment