david6630
david6630

Reputation: 449

Counting the number of http requests in javascript

Is there a way in javascript to count the number of http request that a website does to a server? EXAMPLE: In my local webserver running with apache tomcat i have a simple html page helloworld.html with a style.css file, so when i type "localhost:8080/helloworld.html" the browser does 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 start several number of http get to the webserver.

I'm trying for several days on the web but I have not found anything. I found webrequest api but i think that only chrome extension can use it. I found also chrome.devtools.network API but i can use it only when chrome dev tools is opened.

Upvotes: 5

Views: 6968

Answers (2)

Sriram
Sriram

Reputation: 787

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

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

There is no easy option like finding the individual details like images, css, scripts, etc., But still you can find those if all your resources URL are in some proper 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 have its own caveats like that it will return only successful requests. Pending resources won't be listed

Upvotes: 5

Gnucki
Gnucki

Reputation: 5133

You can count the <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++;
    }
});

This suppose you correctly use relative url. This won't give you any state for the responses (like 404 for instance). Note that indexOf is not working on IE8.

Upvotes: -1

Related Questions