开发者

how to get the html document size with js?

开发者 https://www.devze.com 2023-02-02 13:03 出处:网络
How can you get the actual file size(not in pixels,in bytes) of the document a js script is running o开发者_开发问答n? The solution should work in all major browsers.//

How can you get the actual file size(not in pixels,in bytes) of the document a js script is running o开发者_开发问答n? The solution should work in all major browsers.


//

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');


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消