Track the loading times of individual web pages using JavaScript

Users have been reporting that my existing single-page web application is not performing well, but unfortunately I can't change the code. To address this issue, I want to track the loading time in the following manner:

  1. Record the timestamp of when a user clicks on the page
  2. Record the timestamp of when the page rendering is completed, including ajax requests and other JavaScript functions
  3. Calculate the difference between the two timestamps and send it back to the server

I know how to handle steps 1 and 3 using jQuery, but I'm unsure about the best approach for step 2.

Since this seems like a common scenario, is there a standard toolset available for monitoring performance like this?

Answer №1

Here is a useful tip:

function calculatePageLoadTime() { 
  var startTime = new Date().getTime();
  var loadTime = startTime - performance.timing.navigationStart;
  console.log("User-perceived page loading time: " + loadTime);
}

Answer №2

One way to monitor AJAX performance is by utilizing the global ajaxStop event provided by jQuery.

var startTime = +(new Date());
$(document).ajaxStop(function() {
    var executionTime = +(new Date()) - startTime;
    // perform logging here
});

Although this method may not capture code executed after the final AJAX call, it can still be valuable if the bottleneck occurs before the last call.

Answer №3

One way to accomplish this is by following these steps...

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="jquery.min.js"></script>
    <script type="text/javascript">
        var startTime, endTime, timeDifference;
        function doIt() {
            var startTime = new Date().getTime();
            $.ajax({
                type: 'post',
                url: 'a.php',
                success: function (resp) {
                    endTime = new Date().getTime();
                    timeDifference = endTime - startTime; //The difference in time is captured in milliseconds
                }
            })
        }
    </script>
</head>
<body>
<button style="position: absolute; top:60px" onclick="doIt()">Start</button>
</body>
</html>

Answer №4

Although not a flawless solution, the code below proves effective. It kicks off the timer upon user click and keeps an eye on page content changes via the checkHTML function.

var timeLogging = new Array();
var timeStart;

$(document).click(function() {
    initializeEventLogger();
});

function initializeEventLogger() {
    caption = $(".v-captiontext:first").text();
    timeStart = +(new Date());
    timeLogging.push(new Array(0,0));
    timeLogging[timeLogging.length - 1][0] = timeStart;
}

initializeEventLogger();
// Set up a timer to monitor html changes
window.setInterval(checkHtml, 250);
// Initiate a timer to generate reports
window.setInterval(sendReport, 1000);


var html;
function checkHtml() {
    current = $("body").html();
    if (current != html) {
        html = current;
        var diff = +(new Date()) - timeStart;
        timeLogging[timeLogging.length - 1][1] = diff;
    }
}

function sendReport() {
    if (timeLogging.length > 3) {
        console.log(timeLogging);
        // Perform additional tasks with the collected data
        for (i = 0; i <= timeLogging.length; i++) {
            timeLogging.shift();
        }
    }
}

Answer №5

Have you thought about optimizing your application's markup by storing it in localStorage instead of keeping it all in the page, even when it is hidden? By doing this, you can prevent choking the browser's memory and improve performance. I came across this technique a few years ago when Bing and Google started using it and wrote a blog post about it on the same day I discovered it. Since then, I have implemented this method with great success.

http://example.com/#!article/Optimize-Your-Web-App-with-LocalStorage

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Order of custom code and JQuery in ASP master page

Using an ASP master page to include all the Javascript and jQuery files has presented a challenge for me. Specifically, the jQuery function in OrderManagement.js $(".menu-item").click(function () { window.alert("some text"); }); fails to execute whe ...

Tips for accessing CSS properties on the img tag

I could use some assistance with CSS. I am in the process of creating a tree structure using many <ul> and <li> tags. The issue arises when I have multiple <li> elements with a specific class, each containing an <img> tag. How can ...

I'm encountering issues with this code for a dice game. It's strange that whenever I click the roll dice button, it disappears. Additionally, linking an .css sheet seems to cause the entire page to

I'm currently working with two separate codes: one for HTML and the other for JavaScript. I am facing an issue where the button keeps disappearing when I try to add any CSS styling to it. Even a basic CSS file seems to override everything else and lea ...

transferring documents using multer

As a novice in JavaScript, I am exploring the use of multer for file uploads. Below is my current code: let express = require('express'); let im = require('imagemagick'); let gm = require("gm").subClass({ imageMagick: true }); let ...

execute ajax calls in sequential order

Is there a way to send AJAX requests in a sequential order within a for loop? Take a look at the code snippet below: function ajax_sent(i, btn){ jQuery.ajax({ url : ln_ajax_handle.ajax_url, type : 'post', data : { ...

Using radio buttons and AJAX for switching cases within PHP

My current project involves developing a welfare payment calculator that takes into account income, living situation, and dependents. In my PHP file, I have defined different calculation methods for each scenario as separate 'cases'. The user&apo ...

"Utilizing a Handlebars Helper to Evaluate if Two Values (v1 and v2) are Equal, and Displaying Content from

To make the actual call, I require something along these lines: <script id="messagesTemplate" type="text/x-handlebars-template"> {{#each messages.messages}} {{#each to}} {{#ifCond username messages.sessionUserName}} <h1> ...

Tips for choosing all elements in a form that have a specific class assigned

I am attempting to target all fields in a form with a specific class name and then select all the remaining fields. This is my form: <form style="margin:20px 0" id="myform_2"> <p> Query Name : <input i ...

Switching the markLine in vega lite to a markBar causes it to lose its sorting arrangement

I have created the following data visualization: data = [{"student_name": "student 0", "e": "100.15", "d": "127.81"}, {"student_name": "student 1", "e": "100.30", "d": "189.94"}, {"student_name": "student 2", "e": "100.15", "d": "105.33"}, {"student_nam ...

Various concatenated and compressed JavaScript files across multiple HTML documents within a single application

In my express.js application, I have different routes such as /home and /dashboard. For example, on the home page, I include: jquery.js, underscore.js, somemodule1.js, somemodule2.js. On the dashboard, I include: jquery.js, underscore.js, somemodule3.js, ...

Creating a Cross Fade Animation effect with the combination of CSS and JavaScript

I've been attempting to create a similar animation using html and css. Below gif shows the desired outcome I am aiming for: https://i.sstatic.net/YsNGy.gif Although I have tried the following code, I have not been able to achieve the desired result ...

The React application functions smoothly when executed using react-scripts start, but encounters an "Unexpected SyntaxError: Unexpected Token: <" error upon building

My goal is to deploy my portfolio site using an express server and react-scripts build. Everything works perfectly fine when I run react-scripts start. However, when I try to serve up the build index.js, I encounter the following errors: 2.8b4a0c83.chunk.j ...

hashSync function needs both data and salt to generate the hash

I can't figure out why I am encountering this issue, I have checked the documentation and couldn't find my mistake. Any suggestions? Error: data and salt arguments required const {create} = require('./user.service'); const {genSaltS ...

Traverse through an array of pictures and add the data to a Bootstrap placeholder within HTML markup

In my quest to create a function that populates placeholders in my HTML with images from an array, I am encountering a problem. Instead of assigning each image index to its corresponding placeholder index, the entire array of images is being placed in ever ...

Enhance user interaction in Angular 13 by animating a selected element using just one animation block

I am currently working on a one-page website project to enhance my Angular skills, and I'm facing a challenge with animating multiple DOM elements using a single animation. Defining the animation for each element individually seems like a cumbersome a ...

Angular 4: Modifying the URL without the Component being Displayed

I'm currently facing an issue where I am attempting to link a component from one component using routerLink = "selected" const routes: Routes = [ { path: '', children: [ { path: 'account&apo ...

Can an image map area be identified using radial coordinates?

While I have experience with online Imagemap Generators for rectangular or circular areas in HTML pages, things get a bit tricky when dealing with pie-shaped sections. When trying to make each pie slice a separate area, the image map code generated by thes ...

Blur function not performing as anticipated

I am attempting to achieve a blur effect on a dialog pop-up. Currently, I am using the primeng p-dialog component for this purpose. <p-panelMenu [model]="items" [style]="{'width':'300px'}"></p-panelMenu> <p-dialog head ...

Do I need to utilize getStaticProps along with JSON imports in Next.js?

Is it necessary to use getStaticProps in order to render static data from a JSON or typescript file, or can the data be imported without using getStaticProps? The documentation I read didn't provide a clear answer. projects.tsx const projects: [ { ...

Tips on incorporating the Browserified npm package into an Angular controller

After spending countless hours searching for a solution to integrate Browserify with my project, I found myself struggling to find a tutorial or example that addressed my specific issue. Most resources focused on bundling code rather than demonstrating how ...