Friday, 18 November 2011

TGV.js: JavaScript to reduce page loading times

I'll get to the point now, and waffle on later. TGV.js queues image loading in order of priority and allows JavaScript files to be loaded asynchronously. You can get a minified version of it here (mTGV.js - 3kb), or the full fat version here (TGV.js - 7.8kb). Thanks to Simon Baynes, you can also find it on Github here - It's licensed under the Creative Commons BY license, which means you can use provided you acknowledge it as being written "by Algy Taylor for Conker Media Ltd", or words to that effect in the comments. Usage is as simple as

<script src="/path/to/TGV.js"></script>

Then, for each image which *can* be defered, the tag should be changed to:

<img data-defer-src="/path/to/file" alt="alt text" />"

This will mean that those images won't display if a user doesn't have JS enabled, so make sure that they're not vitally important to the usability of the site!

This problem can (and probably should) be avoided by placing a non-defered image in a noscript tag, as shown in Philip "Spectator"'s comment (#2 in the comments below):

<img data-defer-src="/path/to/file" alt="alt text" />
<noscript><img src="/path/to/file" alt="alt text" /></noscript>

If you want to load JavaScript files asynchronously, you will need to add a little bit more:

<script src="/path/to/TGV.js"></script>
(function() {
TGV.onScriptsReady(function () {
// do things here

And that's yer lot! Although, as a nice side-effect, if you want to make use of some of the internal methods, you're more than welcome to!

  • TGV.onDOMReady(function);
  • TGV.addEvent(element, type, handler);
  • TGV.removeEvent(element, type, handler);

They do what you'd expect - onDOMReady accepts a function to run when the DOM is ready, whilst addEvent and removeEvent are cross browser event handlers.

If you have any suggestions on how to improve this, please drop me a line - either in the comments below, or via email (a taylor at lime pictures dot com).

As with all great inventions, this work was built on the shoulders of giants: Paul Hammond, 'Tobias' off Stack Overflow, Ryan Morr, Peter Paul Koch (ppk), Emil Stenström and Dean Edwards all unwittingly wrote various pieces of this, which I've butchered.