two years agoaddSizes.js: Snazzy automatic link file-size generation

Often in the development of a site I come across the need to display the size of a document next to the link targeting it. I also like to display the type of file the link targets, for example, when linking to pdfs, mp3s or Word documents.

These indications distinguish the 'attachment' link from a normal web link, whilst also giving the user some inkling of the time they will need to wait to view the resulting content.

So I was pretty excited when Simon bounded in from work and enthusiastically demonstrated json-head, a Google App Engine application he built on the train home.

Every file on the web, be it a web page, a text file or whatever has HTTP headers associated with it. This is meta information about the file that is sent before the actual contents of the file itself. Included in this meta information is the size of the document.

You can call json-head with JavaScript (JSONP). It takes the URL of a file on the web and performs a HEAD request against it to return the headers and not the actual content itself. The application then returns this information in JavaScript object notation (JSON) to a callback function you have written.

One of the first things that occurred to me was how this could be used to solve the problem of dynamically adding the file size to links. The resulting script I wrote is being used on this site, so before I explain how it works here's a quick demo of a pdf document and an mp3 file. For a further demo take a look at this basic file.

Using jQuery we first use CSS selectors to find all of the links with the relevant file extensions:

$('a[href$=".pdf"], a[href$=".doc"], a[href$=".mp3"], a[href$=".m4u"]')

For each link, we get the type of the target by splitting the href value on '.' and grabbing the last value. This is the file extension.

jQuery neatly abstracts the faff involved in using JSONP. We pass json-head the URL of the file we want to inspect and the name of the callback function we want it to run with the results. The callback function in this case is '?', which tells jQuery to create a random function name hooked up to the function we pass to getJSON().

var url= "http://json-head.appspot.com/?url="+encodeURI(this.href)+"&callback=?";

$.getJSON(url, function(json){ /* ... */ }

We can now inspect the information sent to us by json-head. If everything went OK we have the size of the file in bytes in the Content-Length header.

var length = parseInt(json.headers['Content-Length'], 10);

Once we have the exact size we need to do a bit more work to get human readable file sizes. We loop through an array to find the largest unit that fits. Once the right size has been found, the script breaks out of the loop storing the unit name and the length to 1 decimal place, so we end up with something like 1.2GB.

for(var i = 0; i < units.length; i++){

  var unitSize = units[i][0];
  var unitText = units[i][1];

  if (length >= unitSize) {

    length = length / unitSize;

    // 1 decimal place
    length = Math.ceil(length * 10) / 10;

    var lengthUnits = unitText;
    break;
  }
}

Now the maths is over, all that remains is to insert the results back into the dom. I am using jQuery's .after() method but if you wanted to insert the size and type directly into the link you could change this to use .append()

I also add the type of the document as a class, to allow for additional styling such as adding an icon. A future version of the script will add the content type to the link as well.

link.after(' (' + type + ' ' + length + ' ' + lengthUnits + ')');
link.addClass(type);

To use this script in your site, simply include jQuery and then the addSizes script itself will do the rest of the magic.

PLEASE NOTE: this may not be 100% reliable due to App Engine being occasionally and unavoidably flakey.

UPDATE: Please see the update to addSizes.

110 comments

  1. Excellent idea! Wonder if it would be worth implementing a caching parameter for json-head to reduce connection overhead for the target server? Could also have a batch request format to call the json-head service with multiple files in one go. I love feature creep.

    P.S. I like the new blog, but wish to lodge a formal complaint concerning the lack of an RSS feed.

    Richard Terry 27th August 2008 21:03permalink.

  2. Thanks Rich, yeah some sort of caching would be a good idea for json-head, I think Si was thinking of implementing that eventually (maybe). The multiple files at once is also an interesting one.

    btw there is an RSS feed ... cunningly hidden in the bar at the top (not sure if that is a good idea or not yet). It is also listed on the about page, probs not obvious enough though!

    Natalie 28th August 2008 00:23permalink.

  3. Ahh, missed the bar! Nice, but could do with arrows or something? Thought it was just a design element. I was mostly confused though because firefox didn't detect the feed and show it in the address bar. Think there might still be a problem with the feed though - google reader showed the HTML source.

    Richard Terry 29th August 2008 01:51permalink.

  4. I was thinking of maybe showing it the first time and hiding it on subsequint visits through use of a cookie. That or show it on all pages but hide it on the homepage.

    You are right, the feed has been intermitantly broaken, should be good now though. Thanks for spotting it not autodetecting the feed, will fix that :)

    Natalie 30th August 2008 01:49permalink.

  5. Great idea and a nice script. I think you should be using encodeURIComponent though, otherwise you won't be getting correct results for links that have an ampersand in them.

    Marko Mrdjenovič 30th August 2008 14:42permalink.

  6. Nice stuff. AppEngine is really starting to make headway as a services platform.

    There needs to be a nice compiled list of these JSON services somewhere.

    Adam 2nd September 2008 14:00permalink.

  7. It is not the case that file size is always sent before the body. HTTP bodies can be chunked-encoded, in which case the file size is not specified before the body is sent.

    Tim Olsen 2nd September 2008 16:13permalink.

  8. Would love to see this as a mozilla ubiquity plugin :)

    https://wiki.mozilla.org/Labs/Ubiquity/Ubiquity_0.1_User_Tutorial

    Guy Fraser 2nd September 2008 16:38permalink.

  9. Excellent work!

    jesusvld 4th September 2008 15:59permalink.

  10. Great idea. This will no doubt come in pretty handy and I'll give it a try. You guys really know your javascript. :)

    Really like the new site by the way!

    Ian 4th September 2008 18:31permalink.

  11. Excellent. This is very useful, so thank you for sharing.
    I do occasionally run in to a bug where some files are listed as being 20 bytes (when they're not) - one being a zip file, and one a pptx file (both of which I added to the list of css selectors in the javascript)

    Nathan 5th September 2008 01:37permalink.

  12. Now everything is showing up as 20 bytes... weird. Any idea on what could be causing that?

    Nathan 8th September 2008 01:39permalink.

  13. Ah just worked it out. The folder the site is in is password protected by the server, which prevents the sizes from being correctly generated.

    Nathan 8th September 2008 02:00permalink.

  14. Seriously sweet this! It's always a pain to add file sizes so anything that can automate is great.
    Thank you very much for sharing this.

    Erwin Heiser 12th September 2008 13:35permalink.

  15. its really great time saver since so much of what we do requires links to different file types on our site. However, it does not seem to work for links that are relative. Is there a solution to this?

    kelly p 12th September 2008 22:33permalink.

  16. love the script, works like a charm for remote links.

    Was wondering if anyone can think of a work around for links that are in a secure folder...
    Even when a user is logged in and the file is availble to download the link size doesn't display. Im assuming because the files are in a secure folder.

    any help would be appreciated

    chris g 14th September 2008 00:03permalink.

  17. kelly p

    for a relative link solution try phps built in filesize() function.

    chris g 14th September 2008 01:50permalink.

  18. thanks for come up with this cool script !

    a joomla 1.0 & 1.5 plugin implementation with this javascript can be found at VivoCiti, http://vivociti.com/content/view/64/53/

    sunwu 19th September 2008 15:57permalink.

  19. ooJSR1 Hello! and <a href="http://trental-fda.viviti.com">trental</a> and http://trental-fda.viviti.com trental and pwbdsr and

    discount methotrexate 21st March 2010 16:48permalink.

  20. The <a href="http://lowest-rate-loans.com">loan</a> suppose to be essential for guys, which want to ground their business. By the way, that's comfortable to receive a car loan.

    Carmella34Pate 3rd April 2010 19:06permalink.

  21. neFo1p http://fgb20gb4hHvdsOOk3rnv.net

    samantas 12th April 2010 22:55permalink.

  22. 6oQRp2 http://www.fovbgbHHvd8cbfi7uss.com

    sammys 13th April 2010 06:21permalink.

  23. oLiHCf http://www.f8dpybvfNnMed027gchhA94jc.net

    lidia 28th May 2010 09:07permalink.

  24. thnaks for sharing

    Medyumlar 29th May 2010 11:47permalink.

  25. Beautiful site, http://www.wallaceterry.com/Members/collection/very-short-skirts/ very short skirts, 38435,

    very short skirts 13th June 2010 19:32permalink.

  26. Very interesting tale <a href=" https://www.stanford.edu/group/smsa/cgi-bin/public/forum/viewtopic.php?id=307 ">young nude lolitas</a> 5614

    Hxavnxfg 14th June 2010 18:08permalink.

  27. Preteen Lolitas Nude HERE!>>

    superlolita 14th June 2010 20:51permalink.

  28. Best Lolitas BBS here >>
    http://premedforum.stanford.edu/viewtopic.php?p=462

    mark 16th June 2010 17:57permalink.

  29. Best preteen lolitas portal

    dobson 16th June 2010 19:16permalink.

  30. Excellent work, Nice Design <a href=" http://premedforum.stanford.edu/viewtopic.php?p=462 ">lolita portal</a> %-(

    Ehxhgcvb 16th June 2010 20:35permalink.

  31. Best top 100 lolita toplist

    sandra 16th June 2010 23:14permalink.

  32. Preteen lolita models tgp http://students.washington.edu/pnpga/forum/profile.php?id=231 Here!>>

    sosa 17th June 2010 00:33permalink.

  33. I like the idea and content of your article.well done.Efforts are good and viewer may concern your thoughts.

    How To Get Pregnant 19th June 2010 05:22permalink.

  34. very best job <a href=" http://rhodes.uthsc.edu/bin/view/Main/JoseffSmithz ">nude lolita</a> 4130

    Vlgpldes 19th June 2010 07:23permalink.

  35. Lolita bbs http://rhodes.uthsc.edu/bin/view/Main/JoseffSmithz welcome

    sandra 19th June 2010 08:44permalink.

  36. This is one of the best posts that I’ve ever seen; you may include some more ideas in the same theme. I’m still waiting for some interesting thoughts from your side in your next post.

    Acai Berry 19th June 2010 09:11permalink.

  37. Preteen lolita models

    merlo 19th June 2010 10:01permalink.

  38. Hey this is really nice information. I was looking for something similar like this. Thanks for this useful information.

    Acai Berry Diet 19th June 2010 10:34permalink.

  39. ajpxlFud

    sLIANENO 23rd June 2010 20:26permalink.

  40. Thank your for your articles. I learn more from here! Thank you ! lace wig

    full lace wigs 25th June 2010 04:25permalink.

  41. doors.txt;7

    Alex 2nd July 2010 03:06permalink.

  42. doors.txt;7

    Alex 2nd July 2010 10:26permalink.

  43. doors.txt;7

    Alex 2nd July 2010 18:01permalink.

  44. doors.txt;7

    Alex 4th July 2010 11:47permalink.

  45. doors.txt;7

    Alex 4th July 2010 11:47permalink.

  46. thanks for come up with this cool script. although it's old. haha..mbt shoes

    RED DEVIL 5th July 2010 08:44permalink.

  47. doors.txt;10

    Alexxus 6th July 2010 18:51permalink.

  48. doors.txt;10

    Alexxus 6th July 2010 18:52permalink.

  49. xGgFtX http://fv7hxwgfjsvgJdnf8hdbKkaldf.com

    grenlickw 8th July 2010 11:39permalink.

  50. YMoaeI http://fbvc9wcb9d5rcvwr83vecDD8sk.com

    grenlickwssv 8th July 2010 12:20permalink.

  51. SngR17 http://www.bhsuddgdggmdGGGjdg7364vcKdh.net

    grenlickws 8th July 2010 14:52permalink.

  52. xlSfvw http://www.66d9bfygkKndOwbvfjhg4U.net

    grenlickwssx 8th July 2010 17:31permalink.

  53. y4aPR7 http://fgnv3GvaPPAAj48bvffsdgl30b.biz

    grenlickwss 8th July 2010 18:03permalink.

  54. doors.txt;10

    Alex 10th July 2010 21:18permalink.

  55. doors.txt;10

    Alex 10th July 2010 21:18permalink.

  56. thanks for come up with this cool script

    payday loan 13th July 2010 13:17permalink.

  57. thank you for good information . and thank you for sharing cool script.

    Resveratrol Ultra 13th July 2010 13:50permalink.

  58. The mortgage loans seem to be important for people, which want to ground their own organization. In fact, it's not really hard to get a consolidation loan.

    home loans 18th July 2010 19:19permalink.

  59. doors.txt;10

    Alex 19th July 2010 07:00permalink.

  60. doors.txt;10

    Alex 19th July 2010 07:00permalink.

  61. <h1><a href="http://www.supra-shoes-cheap.com/supra-tk-society-c-5.html"><strong>Supra TK Society</strong></a>, Supra TK Society</h1><br><br />
    <h1><a href="http://www.supra-shoes-cheap.com/supra-trinity-ns-c-4.html"><strong>Supra Trinity NS</strong></a>, Supra Trinity NS</h1><br><br />
    <h1><a href="http://www.supra-shoes-cheap.com/supra-vaider-c-3.html"><strong>Supra Vaider</strong></a>, Supra Vaider</h1><br><br />

    Supra Vaider 21st July 2010 01:55permalink.

  62. really good, nice .Very informative and trustworthy blog. Please keep updating with great posts like this one. I have booked marked your site and am about to email it to a few friends of mine that I know would enjoy readingwedding dresses

    lingda 21st July 2010 07:20permalink.

  63. <h1><a href="http://www.bestsuprashoes.us/"><strong>supra shoes</strong></a>, supra shoes</h1><br><br />
    <h1><a href="http://www.bestsuprashoes.us/"><strong>supra sneakers</strong></a>, supra sneakers</h1><br><br />
    <h1><a href="http://www.bestsuprashoes.us/"><strong>supra skytops</strong></a>, supra skytops</h1><br><br />

    supra skytops 21st July 2010 08:47permalink.

  64. doors.txt;10

    Alex 23rd July 2010 12:40permalink.

  65. doors.txt;10

    Alex 23rd July 2010 12:40permalink.

  66. doors.txt;10

    Alex 24th July 2010 11:04permalink.

  67. doors.txt;10

    Alex 24th July 2010 22:11permalink.

  68. doors.txt;10

    Alex 24th July 2010 22:11permalink.

  69. doors.txt;10

    Alex 25th July 2010 09:00permalink.

  70. doors.txt;10

    Alex 25th July 2010 09:00permalink.

  71. great blog!

    swiss replica 27th July 2010 02:31permalink.

  72. OwjuXAm

    sXLuyG 28th July 2010 03:01permalink.

  73. Very thank for sharing your posts and you review.many people have replyed here,and i would like to take part in.I'd like to share a Proverb with each other one here that is:Every day of thy life is a leaf in thy history. A Proverbs wiht great sense,i hope everyone would learn something from it. cheap shoes online cheap shoes online

    Gucci outlet 28th July 2010 10:40permalink.

  74. ufc 117 live stream i was looking for this. thanks much!

    Dana 29th July 2010 02:07permalink.

  75. <A href="http://www.gstarmbt.com/mbt-ema-sandals-c-22.html"><strong>MBT Ema</strong></A> completely new shoes. Because of the physiological footwear. <A href="http://www.gstarmbt.com/mbt-fumba-sandals-c-28.html"><strong>MBT Fumba</strong></A>

    discount mbt shoes 30th July 2010 14:36permalink.

  76. snazzy bazzy oh yes

    virility ex 31st July 2010 01:42permalink.

  77. <h1><a href="http://www.radii-420.com/radii-straight-jacket-lifestyle-shoes-yellow-satin-p-74.html"><strong>Radii Straight Jacket Yellow Satin</strong></a>, Radii Straight Jacket Yellow Satin</h1><br><br />
    <h1><a href="http://www.radii-420.com/radii-straight-jacket-skate-board-fashion-shoe-black-p-75.html"><strong>Radii Straight Jacket black</strong></a>, Radii Straight Jacket black</h1><br><br />
    <h1><a href="http://www.radii-420.com/radii-straight-jacket-skate-board-fashion-shoe-green-leather-p-76.html"><strong>Radii Straight Jacket Green Leather</strong></a>, Radii Straight Jacket Green Leather</h1><br><br />

    radii shoes 2nd August 2010 07:48permalink.

  78. YGYsi5 http://fgb7s3Ffjsev7yrbvqqcf7.com

    sandy 2nd August 2010 23:38permalink.

  79. <h1><a href="http://www.chanel-uk.net/chanel-ladies-white-ceramic-watch-h0967-p-14.html"><strong>Chanel Ladies White Ceramic Watch</strong></a>, Chanel Ladies White Ceramic Watch</h1><br><br />
    <h1><a href="http://www.chanel-uk.net/chanel-ladies-white-ceramic-watch-h0968-p-15.html"><strong>Chanel Ladies White Ceramic Watch</strong></a>, Chanel Ladies White Ceramic Watch</h1><br><br />
    <h1><a href="http://www.chanel-uk.net/chanel-ladies-white-ceramic-watch-h1179-p-16.html"><strong>Chanel Ladies White Ceramic Watch</strong></a>, Chanel Ladies White Ceramic Watch</h1><br><br />

    Chanel Ladies White Ceramic Watch 3rd August 2010 01:39permalink.

  80. http://www.efox-shop.com

    I found your site on web and read a few of your other posts. Keep up the good work.
    more info please visit the web for b2c iphone etc.
    Ein seltenes Angebot: Im Handy-Shop des Mobilfunkbetreibers E-Plus steht
    zurzeit das Dual-SIM-Handy Samsung B5722. Das Mobiltelefon für den parallelen
    <a href="http://www.efox-shop.com"><b>Ciphone</b></a>

    airphone 10th August 2010 04:15permalink.

  81. I find it difficult to subscribe RSS feeds, bookmark this site anyway I have is a very useful and complete information.

    elliptical for sale 10th August 2010 22:29permalink.

  82. That was a great piece of information., I enjoyed reading it..,

    Red Bull Hats 11th August 2010 09:10permalink.

  83. These are wonderful! Thank you for finding and sharing

    Wholesale baseball hats 11th August 2010 09:11permalink.

  84. Pretty insightful post. Never thought that it was this simple after all. I had spent a good deal of my time looking for someone to explain this subject clearly and you’re the only one that ever did that. Kudos to you! Keep it up.cheap nfl jerseys http://www.gonnadeal.com

    cheap nfl jerseys 12th August 2010 04:45permalink.

  85. http://suprashoes365.com

    supra shoes 13th August 2010 09:28permalink.

  86. You got a really useful blog I have been here reading for about an hour. I am a newbie and your success is very much an inspiration for me. Acuvue Advance Astigmatism

    Acuvue Advance Astigmatism 15th August 2010 07:10permalink.

  87. nice article, thanks for sharing this whit us!
    if you want to buy<a href="http://www.jerseysusa.com">replica nfl jerseys</a>, just find me on my website..

    replica jerseys 17th August 2010 12:49permalink.

  88. I really enjoyed your blog post. I bookmarked your page so I that can keep track of your future post.

    best home insurance 18th August 2010 06:47permalink.

  89. you are so right and i will be back to read it again. http://www.epayebuy.com

    marco 18th August 2010 11:56permalink.

  90. I really enjoyed your blog post. I bookmarked your page so I that can keep track of your future post. full lace wigs front lace wigs http://www.factorywig.com

    COCO 21st August 2010 19:10permalink.

  91. I really enjoyed your blog post. I bookmarked your page so I that can keep track of your future post. full lace wigs front lace wigs http://www.factorywig.com/

    COCO 21st August 2010 19:11permalink.

  92. I really enjoyed your blog post. I bookmarked your page so I that can keep track of your future post.Louis Vuitton Saumur lv Saumur emilie wallet

    buy louis vuitton 22nd August 2010 15:37permalink.

  93. Thanks for such a great post and the review, I am totally impressed! Keep stuff like this coming

    medyum 23rd August 2010 19:09permalink.

  94. <a href="http://www.barefivefingers.com">fivefingers on line</a>

    cheap fivefingers 24th August 2010 08:25permalink.

  95. wow add size i think its good for me you must know it

    free music download mp3 24th August 2010 09:31permalink.

  96. first time being here. thanks for your info.
    welcome to <a href="http://www.gucci1923.com/gucci-mens-briefcase-34044r-a0v1r-2019-p-329.html">men's briefcase</a>

    guccioutlet 26th August 2010 09:43permalink.

  97. dollar items http://www.amandadollar.com/

    wholesale 26th August 2010 09:44permalink.

  98. www.jerseysusa.com replica jerseys , just find me on my website..

    replica nfl jerseys 30th August 2010 03:38permalink.

  99. Extraordinary regards that your article writes,But view I think that we are different.you can click <a

    href="http://www.auggoodshop.com">me </a> and This is a different place
    <a href="http://www.auggoodshoes.com">this is different</a>

    dear jack 30th August 2010 03:59permalink.

  100. Yiwu Sourcing Agent http://www.amandaiec.com/yiwu_agent/China_detail/Yiwu_sourcing_agent_772.html

    Yiwu Export Agent 30th August 2010 04:58permalink.

  101. etDt5i http://djb3jDdmjckow30cnjcmd61l0dy.com

    samanta 30th August 2010 11:35permalink.

  102. <a href="http://www.nfljerseyse.com/dallas-cowboys-jerseys " title="Dallas Cowboys Jerseys ">Dallas Cowboys Jerseys </a>

    cheap nfl jerseys 31st August 2010 03:03permalink.

  103. Great idea and a nice script.

    wholesale nfl jerseys 31st August 2010 04:09permalink.

  104. hey buddy,this is one of the best posts that I’ve ever seen; you may include some more ideas in the same theme. I’m still waiting for some interesting thoughts from your side in your next post.

    wholesale nfl jerseys 31st August 2010 16:12permalink.

  105. Help me to find the, http://cre.ations.net/creator/kimkardashiansextape kim kardashian sex tape free, :-OOO,

    Cheap kim kardashian sex tape 31st August 2010 19:58permalink.

  106. being here. thanks for your info

    masodfjisadue 1st September 2010 03:08permalink.

  107. being here. thanks for your info.

    replica watches 1st September 2010 08:10permalink.

  108. <p>welcome to our site buy replica watches.</p>

    replica watches 1st September 2010 08:16permalink.

  109. Many women like coach purses for their for their good looking ,high quality and good after service. Comapared with coach bags without and brands ,buying a coach purse may cost you a lot of money.Because of that,now many people try to buy cheap mbt shoes than expensive one from the coach outlet stores online.Come on and heva look.Hope you can enjoy your shopping time here.

    b1@yahoo.com 1st September 2010 20:14permalink.

  110. 954ghjghjg

    watchstore 2nd September 2010 08:34permalink.

Line breaks are preserved; URLs will be converted in to links.

Enter your own, valid XHTML. Allowed tags are: a, p, blockquote, ul, ol, li, dl, dt, dd, em, strong, dfn, code, q, samp, kbd, var, cite, abbr, acronym, sub, sup, br, pre

27th August 2008

You are reading "addSizes.js: Snazzy automatic link file-size generation" written by Natalie Downe on the 27th of August 2008 at 12:48 am.

Next: dConstruct and my sisters graduation, a busy week!

Previous: links for 2008-01-29