How to Measure Page Loading Time with JavaScript

This approach demonstrates how to measure the loading time from the moment a user clicks on a link until the destination page fully loads. It’s particularly useful for tracking the performance of pages within a sales funnel.

Attach an event listener to the desired links to record the timestamp when a user initiates navigation:

document.addEventListener('click', function(event) {
  const target = event.target.closest('.link');
  if (target) {
    const timeThen = Date.now();
    localStorage.setItem('ip2timing', timeThen.toString());
  }
});

Retrieve Stored Data and Send Timing Information

Upon loading the destination page, retrieve the stored timestamp and calculate the duration. Then, send this data to a specified URL for storage or analysis:

window.addEventListener('load', function() {
  const ipElement = document.getElementById('ip');
  if (!ipElement) return;

  const currentIP = ipElement.textContent || '';
  const storedTime = localStorage.getItem('ip2timing');
  if (!storedTime) return;

  const timeThen = parseInt(storedTime, 10);
  const timeNow = Date.now();
  const duration = (timeNow - timeThen) / 1000; // duration in seconds

  const pageId = '7'; // Replace with dynamic value as needed

  // Function to send a ping by loading an image
  function sendPing(url, timeout = 1500) {
    return new Promise((resolve, reject) => {
      const img = new Image();
      let timer;

      img.onload = () => {
        clearTimeout(timer);
        resolve({ status: 'success', duration: Date.now() - timeNow });
      };

      img.onerror = () => {
        clearTimeout(timer);
        resolve({ status: 'error', duration: Date.now() - timeNow });
      };

      timer = setTimeout(() => {
        img.src = ''; // Cancel the image load
        reject({ status: 'timeout', duration: timeout });
      }, timeout);

      img.src = `${url}?cache=${Date.now()}`;
    });
  }

  // Only send the ping if the IP matches
  if (currentIP === currentIP) {
    const pingUrl = `https://www.example.com/search-timing.php?duration=${duration}&page_id=${pageId}&when=${timeNow}`;
    sendPing(pingUrl)
      .then(response => {
        // Handle successful ping
        console.log('Ping response:', response);
      })
      .catch(error => {
        // Handle ping error
        console.error('Ping error:', error);
      });

    localStorage.removeItem('ip2timing');
  }
});

Ensure that the element with the ID ip exists on the destination page and contains the user’s IP address or a unique identifier.

Replace '7' with the appropriate page_id value, which can be dynamically set using data attributes, JavaScript variables, AJAX calls, or server-side rendering.

The sendPing function simulates a ping by loading an image from the specified URL. This method is commonly used to send lightweight tracking requests without affecting page performance.

on in AJAX and Fetching Data | Last modified on

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *