Reputation: 305
I want to get the document size, when the page is ready. (just in time after server request).
document.addEventListener("DOMContentLoaded", function (event) {
var pageSizelenght = document.documentElement.outerHTML.length;
//});
This does not give me the exact result with chrome dev-tools document type file in network section.
F.e the dcoument size is shown as 1.5 MB, but in the code it returns 1.8MB with document.documentElement.outerHTML.length
If it is not proper way, how can I get the document size listed in network section? If you can help me, so much appreciated.
Upvotes: 0
Views: 334
Reputation: 136698
As has been said in comments, the outerHTML
is a serialization of the DOM representation after parsing of the original markup. This may be completely different than the original markup and will most likely not match in size at all:
const markup = "<!doctype html><div><p><div>foo";
// DOMParser helps parsing markup into a DOM tree, like loading an HTML page does
const doc = (new DOMParser()).parseFromString(markup, "text/html");
const serialized = doc.documentElement.outerHTML;
console.log({ serialized });
console.log({ markup: markup.length, serialized: serialized.length });
To get the size of the original markup you can call the performance.getEntriesByType("navigation")
method, which will return an array of PerformanceNavigationTiming
objects, where you'll find the one of the initial document (generally at the first position).
These PerformanceNavigationTiming
objects have fields that let you know the decoded-size of the resource, its coded-size (when compressed over the wire), and its transferred-size (can vary if cached).
Unfortunately, this API doesn't work well for iframes (moreover the ones that are fetched through POST requests like StackSnippets), so I have to outsource the live demo to this Glitch project.
The main source is:
const entry = performance.getEntriesByType("navigation")
// That will probably be the first here,
// but it might be better to check for the actual 'name' of the entry
.find(({name}) => name === location.href);
const {
decodedBodySize,
encodedBodySize,
transferSize
} = entry;
log({
decodedBodySize: bToKB(decodedBodySize),
encodedBodySize: bToKB(encodedBodySize),
transferSize: bToKB(transferSize)
});
function bToKB(b) { return (Math.round(b / 1024 * 100) / 100) + " KB"; }
Upvotes: 1