How to Incorporate Application Insights into a JavaScript Web App


Have you ever wondered why your site is painstakingly slow? Of course you have. Wouldn’t it be nice if you could see why exactly it’s being sluggish with the glance of an eye? Using Application Insights, you can diagnose where your site is hanging. Additionally, you can track custom user events on your page. You can then parlay these analytics into UI/UX or marketing decisions involving your site.

Prerequisites

  • You will need an Azure subscription
    • Students are eligible to obtain certain Azure benefits for free through a student Azure account. To access it, they first need to first activate their DreamSpark subscription, which is also free. No credit card is required.
    • Anyone can access a free one month trial of Azure here. A credit card is required, but it will not be debited.
  • You will need some basic understanding of JavaScript and how to develop web apps with JavaScript. You will also need a JavaScript web app to incorporate your code into and get insights from.
  • You will need a text or code editor, such as notepad or Visual Studio Code.

Creating and implementing your Application Insights resource

Open your browser and visit portal.azure.com and sign in using your DreamSpark Azure enabled email. You will be redirected to complete the sign-in process.

clip_image002

Once logged in, you will be brought to the Azure portal page, which is the starting point for any Azure adventure. Go to the top left corner and click NEW.

clip_image004

Then click on Developer Services followed by Application Insights

clip_image006

The setup should be straightforward. Give a name for your Application Insights resource. There’s nothing particular you need to do when you name, it’s purely for your convenience when browsing your various Azure services. You will the need to click Application Type.

clip_image008

From the Application type options, choose ASP.NET Web Application. Now the website doesn’t necessarily have to be ASP.NET, because the client side code is JavaScript and will work with whatever regardless of your backend framework.

Once you complete that, you can click create. The Pin in Startboard checkbox allows you to have your resource displayed as a tile on the Azure portal page.

clip_image010

You’ll have to wait a few moments for the resource to provision, then you’ll be taken to the Application Insights summary page. Once there, click on the cloud with the thunderbolt, which will take you to the quick start page.

clip_image012

Once there, click on “Get code to monitor my web pages.”clip_image014

You will want to copy analytics code and paste it right before < /head> tag of any web page you want to use it on. If your website has any form of master template page, you can put it there to have it applied everywhere at once. In an ASP.NET MCV web app for example, it would go in View\Shared\_Layout.cshtml.

If you’re using a popular framework like AngularJS, you can use an adaptor to use Application Insights. Scroll down to see instructions for AngularJS.

clip_image016

clip_image018

Utilizing Application Insights

You will now have to run or publish your web app and then have it used for a while to generate data.

If you go back to your Application Insights summary page and click refresh, you should see that one of the charts, browser page load, have data points plotted on it. The other ones are currently not displayed because we only implemented client side telemetry (and not on the server).

clip_image020

You can click Time Range to get better granularity for your data points. Click on the chart to get more insight into our data.

clip_image022

Our data is now separated into standard timings, the definitions of which are set by the W3C. You can use this to troubleshoot bottlenecks in your page loading.

clip_image024

At the bottom of the page, you’ll notice that the page load time is further divided by URL. If you want to see the performance of the pages over time, double click the chart and change its type to Line in the Chart details panel.

clip_image026

Custom Page Events

You can use the Application Insights API to get custom reporting from your web pages. The API is fairly comprehensive and can be used to collect a variety of data points from your application.

We can use this to do something like custom page counts. Normally the page counts up when a user loads a new page. You might something different however if you have a single page app with tabs. It suffices to include this code wherever you have your tab events:

appInsights.trackPageView(myPageName);

For more information on using the custom API, you can check out the official Azure documentation.

Using Application Insights with Angular.js

Application Insights can also be used with popular frontend frameworks like Angular. This can make it easy to collect insights from a Single Page App.

To implement Application Insights on an Angular web app, first get the Angular module here: http://ngmodules.org/modules/angular-appinsights

Then use the same code snippet we used earlier, but remove certain lines:

<!--
To collect end-user usage analytics about your application, insert the following script into each page you want to track. Place this code immediately before the closing </head> tag, and before any other scripts. Your first data will appear automatically in just a few seconds.
-->

<script type="text/javascript">
   
var appInsights=window.appInsights||function(config){
        function s(config){t[config]=function(){var i=arguments;t.queue.push(function(){t[config].apply(t,i)})}}var t={config:config},r=document,f=window,e="script",o=r.createElement(e),i,u;for(o.src=config.url||"//az416426.vo.msecnd.net/scripts/a/ai.0.js",r.getElementsByTagName(e)[0].parentNode.appendChild(o),t.cookie=r.cookie,t.queue=[],i=["Event","Exception","Metric","PageView","Trace"];i.length;)s("track"+i.pop());return config.disableExceptionTracking||(i="onerror",s("_"+i),u=f[i],f[i]=function(config,r,f,e,o){var s=u&&u(config,r,f,e,o);return s!==!0&&t["_"+i](config,r,f,e,o),s}),t
    };
   
({//<—remove this
        instrumentationKey:"your key here"//<-- remove this
    })//<-- remove this

    window.appInsights=appInsights;
    appInsights.trackPageView(); //<-- remove this

</script>

Once you remove them, your code should look like this:

<!--
To collect end-user usage analytics about your application, insert the following script into each page you want to track. Place this code immediately before the closing </head> tag, and before any other scripts. Your first data will appear automatically in just a few seconds.
-->

<script type="text/javascript">
   
var appInsights=window.appInsights||function(config){
        function s(config){t[config]=function(){var i=arguments;t.queue.push(function(){t[config].apply(t,i)})}}var t={config:config},r=document,f=window,e="script",o=r.createElement(e),i,u;for(o.src=config.url||"//az416426.vo.msecnd.net/scripts/a/ai.0.js",r.getElementsByTagName(e)[0].parentNode.appendChild(o),t.cookie=r.cookie,t.queue=[],i=["Event","Exception","Metric","PageView","Trace"];i.length;)s("track"+i.pop());return config.disableExceptionTracking||(i="onerror",s("_"+i),u=f[i],f[i]=function(config,r,f,e,o){var s=u&&u(config,r,f,e,o);return s!==!0&&t["_"+i](config,r,f,e,o),s}),t
   
};
   
window.appInsights=appInsights;

</script>

Put the code in a script then include the code at the bottom of your <body> tag on your SPA’s shell page. Right above it, put the following reference:

<script type="text/javascript" src="angular-appinsights.js"></script>

Finally, you have to initialize your angular-appinsights module.

angular.module('insightsApp', ['ngRoute', 'angular-appinsights'])
   
.config(['$routeProvider', 'insightsProvider', function ($routeProvider, insightsProvider) {

    $routeProvider
       
.when('/', {
           
templateUrl: "home.html",
           
controller: 'homeController'
       
})
       
.when('/about', {
           
templateUrl: "about.html"
       
});

    // Add key
   
insightsProvider.start(‘AppInsightsKey');

}])

Your code should now be tracking page views. For additional instructions on logging custom metrics, visit the github repo of the module: https://github.com/johnhidey/angular-appinsights

Comments (0)

Skip to main content