Last active
May 16, 2022 16:45
-
-
Save mojaray2k/6619426 to your computer and use it in GitHub Desktop.
Use jQuery to send a HEAD request with AJAX and get the size of a file without downloading it. This snippet places the size of the file in braces next to its name. The script issues a HEAD request, which only returns the headers and not the actual content of the file, which means that these requests are fast and lightweight.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(' (' + size + ')'); | |
} | |
}); | |
}); | |
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]; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Display files sizes next to download links</title> | |
</head> | |
<body> | |
<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> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> | |
<script type="text/javascript" src="filessizes.js"></script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does this work with CORS?