Skip to content

Instantly share code, notes, and snippets.

@golman
Created May 12, 2013 19:10
Show Gist options
  • Save golman/5564564 to your computer and use it in GitHub Desktop.
Save golman/5564564 to your computer and use it in GitHub Desktop.
Display file sizes next to download links
// Loop all .fetchSize links
$('a.fetchSize').each(function(){
// Issue an AJAX HEAD request for each one
var link = this;
$.ajax({
type: 'HEAD',
url: link.href,
complete: function(xhr){
var size = humanize(xhr.getResponseHeader('Content-Length'));
// Append the filesize to each
$(link).append(' (' + type + ')');
}
});
});
function humanize(size){
var units = ['bytes','KB','MB','GB','TB','PB'];
var ord = Math.floor( Math.log(size) / Math.log(1024) );
ord = Math.min( Math.max(0,ord), units.length-1);
var s = Math.round((size / Math.pow(1024,ord))*100)/100;
return s + ' ' + units[ord];
}
// html
// <a href="001.html" class="fetchSize">First Trickshot</a>
// <a href="034.html" class="fetchSize">This Trickshot</a>
// <a href="ball.png" class="fetchSize">Ball.png</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment