如何用js获取html文档的大小?
如何获取 js 脚本正在运行的文档的实际文件大小(不是以像素为单位,以字节为单位)?该解决方案应该适用于所有主要浏览器。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
//
//
您可以通过 ajax 重新获取页面并以字符串形式获取其长度,但这不是最佳选择,因为它将触发另一个 HTTP 请求并且必须等待它。
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.
这与您仅使用 JS 查看页面的完整源代码差不多:
您可以使用返回的字符串作为文件大小的起点。如果您需要考虑图像,则必须通过遍历 DOM 树并检查每个
img
元素来手动添加它们的大小。这可以通过 jQuery 或类似的库选择器轻松完成:$("img").each(function() {...});
如果您需要进一步考虑 Flash 和 Java 等元素,完全用JS是没有办法做到这一点的。您必须运行 AJAX 请求并让服务器告诉您引用文件的大小。
This is about as close as you'll get to viewing the full source for a page using only JS:
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.