Reputation: 1078
How can you get the actual file size(not in pixels,in bytes) of the document a js script is running on? The solution should work in all major browsers.
Upvotes: 3
Views: 2075
Reputation: 104760
//
function hrefSize(){
try{
var O= new XMLHttpRequest;
O.open("HEAD", document.URL, false);
O.send(null);
if(O.status== 200){
return O.getResponseHeader('Content-Length');
}
else return 0;
}
catch(er){
return 0;
}
}
alert(hrefSize()+' bytes');
Upvotes: 4
Reputation: 3199
This is about as close as you'll get to viewing the full source for a page using only JS:
document.documentElement.innerHTML
You could use the returned string as a starting point for the file size. If you need to consider images, their sizes would have to be added on manually by traversing the DOM tree and inspecting each img
element. This could be done easily via a jQuery or similar library selector:
$("img").each(function() {...});
If you need to further consider elements like Flash and Java, there is no way to do this completely with JS. You'd have to run an AJAX request and let the server tell you the sizes of referenced files.
Upvotes: 0
Reputation: 45568
You could propably refetch the page via ajax and get the length of it as a string, but this will be suboptimal because it will trigger another HTTP request and have to wait for it.
Upvotes: 1