Counting the number of HTTP requests in javascript

Is there a way in javascript to count the number of HTTP requests a website makes to a server? EXAMPLE: In my local web server running apache tomcat, I have a simple helloworld.html html page with a style.css file, so when I type "localhost: 8080 / helloworld.html" the browser makes two requests: one for helloworld.html and one for style.css.

My goal is to show this number on helloworld.html for a video element, when I play it, multiple HTTP files are run to the web server.

I have been trying for a few days on the internet, but found nothing. I found the webrequest api but I think only chrome extension can use it. I found the chrome.devtools.network API as well, but I can only use it when the chrome dev tools open.

+3


source to share


2 answers


With the window.performance API provided by HTML5, there is an easy way to find out the total number of external resources a page is loading.

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

      

There is no easy way to find individual details like images, css, scripts, etc. But you can still find them if all your resource URLs are in some correct format, like http://example.com/img/sample.jpg or http://example.com/scripts/app.js or http: //example.com/styles/master.css



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

      

Note: using _ for filtering. you can use without _. This method also has its own caveats, as it will only return successful requests. Pending resources will not be listed

+2


source


You can consider <link>

and <script>

manually (for a simple page without ajax).

With 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++;
    }
});

      

Let's assume you are using the relative URL correctly. This will not give you any state for responses (e.g. 404). Please note that indexOf

does not work on IE8.

-1


source







All Articles