计算 javascript 中的 http 请求数

Counting the number of http requests in javascript

本文关键字:请求 http 中的 javascript 计算      更新时间:2023-09-26

javascript中有没有办法计算网站对服务器的http请求数量?示例:在运行 apache tomcat 的本地网络服务器中,我有一个简单的 html 页面 helloworld.html带有 style.css 文件,所以当我输入"localhost:8080/helloworld.html"时,浏览器会执行两个请求,一个用于 helloworld.html一个用于 style.css。

我的目标是在helloworld上显示这个数字.html对于视频元素,当我播放它时,它会启动几个http到达网络服务器。

我在网上尝试了几天,但我什么也没找到。我找到了网络请求 api,但我认为只有 chrome 扩展程序可以使用它。我还找到了chrome.devtools.network API,但我只能在打开chrome开发工具时使用它。

使用HTML5提供的window.performance API,有一个简单的选项来找出页面加载的外部资源总数。

var totalNoOfResrouces = window.performance.getEntriesByType("resource").length;

没有简单的选择,例如查找图像,css,脚本等单个详细信息,但是如果您的所有资源URL都采用某种适当的格式,例如 http://example.com/img/sample.jpg,http://example.com/scripts/app.js 或 http://example.com/styles/master.css,您仍然可以找到这些

_.filter(window.performance.getEntriesByType("resource"),function(a){ return a.name.indexOf("/img/") > 0 });

注意:使用 _ 进行过滤。可以在不使用 _ 的情况下使用。此方法也有其自己的警告,例如它将仅返回成功的请求。挂起的资源不会列出

您可以手动计算<link><script>(对于没有 ajax 的简单页面)。

使用 JQuery:

var requestsNumber = 1; // The document itself.
$('link').each(function() {
    var href = $(this).attr('href');
    if (href && -1 === href.indexOf('http://')) {
        requestNumber++;
    }
});
$('script').each(function() {
    var src = $(this).attr('src');
    if (src && -1 === src.indexOf('http://')) {
        requestNumber++;
    }
});

这假设您正确使用相对 url。这不会给你任何响应状态(例如 404)。请注意,indexOf不适用于 IE8。