Detecting Connection Speed in .NET Using jQuery
A recent web project called for the ability to detect a user’s connection speed to determine whether to serve low or high quality videos to the browser. After investigating some pricey third-party applications, we decided to come up with our own solution.
Our approach would involve displaying a large (over 1MB) image on a web page and recording the time between the browser initiating the call and the image being fully loaded.
In summary, here is how we accomplished this task using the jQuery framework:
- The user visits our Speed Test page.
- The Speed Test page is delivered to the browser from the server with a timestamp indicating when the page request was made.
- Once the large image contained on the Speed Test page is completely loaded, the page uses jQuery to make an asynchronous call to a remote page passing the original timestamp from step 2.
- The page that accepts the asynchronous takes the difference between the original timestamp and the server’s current time and calculates an approximate download speed.
Now on to the details:
Speed Test Page
We started by creating our speed test page and placing our 1MB image on it. To prevent the from caching, which would skew our speed calculations, we added a querystring with a series of random numbers to the source of the image. The random number is generated on page load and dynamically inserted into the ImageUrl property of an ASP Image control.
Dim r As New Random
Dim rnd As Integer = r.Next(1111, 9999)
Image1.ImageUrl = "our-test-image.jpg?v=" & rnd.ToString
End Sub
Attach jQuery
Since we’re using jQuery, we need to attach the library. This following code uses the GooglejQueryCDN. In case jQuery fails to load from the Google servers, we fallback to a local copy.
<script>
!window.jQuery && document.write(unescape('%3Cscript src="js/jquery-1.5.1.min.js"%3E%3C/script%3E'))
</script>
See the sweet HTML5 Boilerplate for more on this.
Ajax/jQuery.get
$(window).load(function () {
$.get("test.aspx", { string: "<%=DateTime.Now.ToString()%>" }, function (data) {
$(".speed").html(data);
})
});
</script>
Using jQuery’s $.get() data transfer method, we are able to call a remote page, pass a variable, and receive some data back. Let’s step through each line to see exactly what is happening here.
jQuery’s $(document).ready handler fires off as soon as all the DOM elements are loaded. In our case, that happened before our large image has completed loading. Since we are trying to determine how long it took for that image to load, we cannot make the call to our remote page until the image has done so. The $(window).load handler, however, waits until all page elements have finished loading. This is a fits perfectly with our needs.
Once our 1MB test image completes loading on the user’s browser, jQuery calls our remote page test.aspx. Our variable string is also passed to our remote page as a querystring. The value of this querystring is set to the current date and time when the server initially compiles the page to send to the visitor. So, string is essentially the date and time at which the user requested the page.
Our remote page, test.aspx, calculates the connection speed and passes the value back to the page that initiated the call. We will take a look at those calculations below.
When our page receives the data back from the remote page, it updates the contents of an HTML tag with a class of speed (i.e.: <span class="speed"></span>).
The Remote Page
The remote page, test.aspx, actually performs all of our calculations to determine the user’s (approximate) connection speed.
Dim startTime As Date = CType(Request.QueryString("string"), Date)
Dim endTime As Date = DateTime.Now
Dim span As TimeSpan = endTime.Subtract(startTime)
Dim dSpan As Double = span.TotalSeconds
Dim connSpeed As Decimal = 1055 / dSpan
Response.Write(String.Format("{0:#.##}kbps", connSpeed))
End Sub
On page load, we grab the date and time from our string querystring. Then, we get the current date and time and use these two values to calculate the number of seconds that have passed between the two dates. We end up with the number of seconds it took for the page completely load in the user’s browser and make a call out to the remote page.
We divide the size of our test image (in this case 1055 kilobytes) by the number of seconds between the startTime and endTime. Finally, we pass the resulting value back to our initial page with some appropriate formatting.
Conclusion
Although the results of this speed test are not exact, it is close enough for us to determine whether the visitor is using a high-speed broadband or slow dial-up connection. By saving the resulting information into a database table, we can recall the info when determining what quality video the user should be served.
Comments
Posted by: Danilo
I wanted to send you one very small remark to give many thanks over again with your pleasant tactics you have shown on this site. It is simply extremely open-handed with you to provide extensively what exactly most people might have advertised for an ebook to help make some bucks on their own, most importantly considering that you could possibly have tried it if you ever decided. Those strategies additionally worked as a good way to fully grasp many people have the same passion the same as my very own to realize lots more on the subject of this matter. I think there are thousands of more pleasant moments ahead for individuals who read through your blog post.