Read Size Of Current Document From Javascript
Solution 1:
How about document.documentElement.innerHTML.length
?
Solution 2:
document.documentElement.innerHTML.length
as per @meder is probably good enough. It won't be exact because it returns a serialisation of the current page DOM and not the original HTML source.
For static pages that won't matter as it'll just be the case of an extra close tag here, different attribute quoting there... but if there's lots of page content created on the fly from script, that content will count in innerHTML
despite not being present in the original source, which could throw your calculation out.
If you need to find out the actual resource length, you'd need to fetch the page again, which you could do using an XMLHttpRequest
on the current URL:
var xhr= new XMLHttpRequest();
xhr.onreadystatechange= function() {
if (this.readyState!==4) return;
alert(this.responseText.length);
};
xhr.open('GET', location.href, true);
xhr.send();
(This can't be done if the page is the result of a POST request though.)
This will give you a size in characters. If you are using an single-byte encoding like ISO-8859-1, the network-load byte size will be the same. If you're using UTF-8, then you can find out the byte size by converting the string to UTF-8-bytes-as-code-units, for which there's a quick idiomatic hack:
var bytes= unescape(encodeURIComponent(this.responseText));
alert(bytes.length);
If you are unfortunate enough to be using a non-UTF-8 multibyte encoding you can't really do much here; you'd have to include full mapping tables for the encoding, which for East Asian encodings would be insanely large.
Solution 3:
How about this?:
/*
* This script determines the size of the current page in bytes.
* But why does the 2nd length differ from the first?
*/var len=document.getElementsByTagName("html")[0].innerHTML.length;
var len2=document.getElementsByTagName("head")[0].innerHTML.length + document.getElementsByTagName("body")[0].innerHTML.length;
//document.body.innerHTML.lengthalert('Page Size: '+len +' bytes');
alert('Page Size2: '+len2+' bytes');
It seems to work ok, BUT NOT great. As it gives two different lengths. But why? Ugh! This formatting is killing me.
EDIT: Can somebody please fix this formatting? My browser isn't working right, apparently. Firefox 15.x
EDIT: fixed formatting
Post a Comment for "Read Size Of Current Document From Javascript"