Is the use of addEventListener("load",... creating an excessive number of XmlHttpRequests?

Consider a scenario where you have the following JavaScript code running in a Firefox plugin, aimed to execute an XmlHttpRequest on a page load:

function my_fun(){

var xmlHttpConnection = new XMLHttpRequest();
    xmlHttpConnection.open('GET', globalUrl+'/call_this.php', true);
    xmlHttpConnection.onreadystatechange=function(){
        if (xmlHttpConnection.readyState == 4 && xmlHttpConnection.status == 200) {
            var serverResponse = xmlHttpConnection.responseText;
            do_stuff();
            clearTimeout(xmlHttpTimeout);
            xmlHttpConnection.abort();
       }
 };

 xmlHttpConnection.send(null);
 xmlHttpTimeout = setTimeout(function (){
                                 do_other_stuff();
                                 xmlHttpConnection.abort();
                                 clearTimeout(xmlHttpTimeout);
                             },5000);
}

container.addEventListener("load", my_fun, true);

Upon invoking my_fun(), the access logs on the Apache server display entries like this:

<client-ip> - - [06/Nov/2014:10:40:04 -0500] "GET /call_this.php HTTP/1.1" 200 1 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0"

If there are 4 client connections on the server, it's possible that within one second, this log line appears multiple times simultaneously, even originating from just one client. While there may be fewer than 5 pings per second most of the time, intermittent spikes attributable to call_this.php could escalate the frequency.

What could be causing this behavior? One potential culprit might be the

container.addEventListener("load", my_fun, true);
. Could this be inaccurately tracking loads, especially when hidden URLs are being loaded on the page? If so, how can this issue be rectified? (Edit: Would utilizing an observer service yield better results?)

Answer №1

A peculiar issue caught my attention:

Take a closer look at this section:

container.addEventListener("load", function(){customFunction();}, true);

You might want to modify the function declaration as follows:

function customFunction(){
...

to

customFunction = function(){
...

Answer №2

After extensive investigation, it has been determined that there may be an issue with the event listener in this particular scenario within a Firefox plugin. A more effective approach would be to utilize Mozilla observers, which have shown to significantly reduce server pings based on empirical tests.

I would like to express my gratitude to Noitidart for providing a similar solution to a different problem.

var customObserver = {
register: function() {
    var observerService = Components.classes["@mozilla.org/observer-service;1"]
    .getService(Components.interfaces.nsIObserverService);
    observerService.addObserver(this, TOPIC_MODIFY_REQUEST, false);
},
observe : function(aSubject, aTopic, aData) {
    if (TOPIC_MODIFY_REQUEST == aTopic ) {
        var url;
        aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);

        url = aSubject.URI.spec;
        url = encodeURIComponent(url);

        var oHttp = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);
        if (oHttp.loadFlags & Components.interfaces.nsIHttpChannel.LOAD_INITIAL_DOCUMENT_URI) {
            //is top level load
            my_fun(); //Same function as in original question
        }
    }
}       
} 

customObserver.register();

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

Set up an event listener for when geolocation permission is approved

My Setup: I've written some basic code snippet below: const onSuccess = () => { console.log('success'); } const onError = () => { console.log('error'); } navigator.geolocation.getCurrentPosition(onSuccess, onError) ...

Learn how to implement form validation on a sliding form in just 5 easy steps using jQuery

I am new to programming and I struggle to comprehend complex JavaScript code written by others. Instead of using intricate code that I don't understand, I would like to request help in creating a simplified jQuery script for me to implement. Current ...

Utilize Object literal manipulation to include properties in a specific sequence

Working on a tool to generate Nassi-Shneiderman diagrams online, where each diagram is represented as an object literal with unlimited possible children. As I aim to add a sequence into the while loop following the first sequence, I encounter the challeng ...

Fix a typing issue with TypeScript on a coding assistant

I'm struggling with typing a helper function. I need to replace null values in an object with empty strings while preserving the key-value relationships in typescript // from { name: string | undefined url: string | null | undefined icon: ...

Present a Java-generated JSON object on a JSP page using JavaScript

Hello, I am currently working on creating a Json object in Java and would like to display the same JSON object in JSP using JavaScript. Essentially, I am looking to add two more options in my select box using Ajax. The Ajax is being called and I can see th ...

Initially Missing Child Props in Parent Component

I am currently working on an application that utilizes a nutrition API to fetch information such as calories and more. One of the key features I am developing is the ability for users to set their daily calorie target along with the percentage breakdown fo ...

Node.js poses a challenge when it comes to decoding incoming request data

I am attempting to create a sample login page using the combination of node, express, and angularjs. Displayed below is my login view: <div class="login-page"> <div class="login-page-content"> <div style="margin-top:30px;padding:10px;w ...

Issue with Browsersync functionality in Docker

My Node.js app is facing an issue with Gulp, Browsersync, and Docker. When I run gulp watch locally, everything functions correctly. However, when I utilize docker-compose up, I encounter an error Cannot GET / The Browsersync UI on port 3001 is operat ...

Developing dynamic progress indicators in Django - A guide

I'm in the process of figuring out how to create a real-time progress bar for updating. The idea is that the server will update the user periodically on the current progress. Fortunately, I am familiar with making an Ajax call using Django and jQuery ...

Utilize the Multer file upload feature by integrating it into its own dedicated controller function

In my Express application, I decided to keep my routes.js file organized by creating a separate UploadController. Here's what it looks like: // UploadController.js const multer = require('multer') const storage = multer.diskStorage({ dest ...

Do GPU-intensive animations get impacted by the CPU's load?

I have set up a special compositing layer for a div with the following unique styles: div { position: absolute; height: 50px; width: 50px; background: #900; top: 100px; left: 200px; will-change: transform; transform: translateZ(0); } Afte ...

Creating a button that allows updates without refreshing the page can be achieved by implementing

Here are the items I have: <table> <tr> <th> id </th> <th> name </th> <th> update </th> </tr> <tr> ...

The getServerSideProps function in Next.js is only executed once, meaning it won't retrieve fresh data when accessed via next/router

I'm working on a Next.js application with Server-Side Rendering (SSR) where I have an async function called getServerSideProps that is exported like this: export const getServerSideProps = getGenericServerSideProps([""]); The getGenericServerSideProp ...

Storing values in an array when checkboxes are selected within an ng-repeat loop in AngularJS

I am facing a situation where I need to populate an array with values when a checkbox is checked within an ng-repeat iteration. <li ng-repeat="player in team.players"> <div class="row"> <div class="col-md-3 m-t-xs"> <inp ...

Security Vulnerability in Ajax Callback Breakpoints

Imagine I have the following code snippet (partially pseudocode) $.ajax({ url: "/api/user", success: function(resp) { var data = JSON(resp) if (data.user.is_admin) // do admin thing else // do somet ...

What is the reason behind the Typescript compiler not converting .ts files to .js files automatically?

Displayed below are the folders on the left showcasing my Typescript file in /src (blue) compiled into Javascript in /dist (purple) using tsc. https://i.stack.imgur.com/7XNkU.png In the source file on the left, there is a reference to a .ts module file t ...

Can you explain the contrast between window.performance and PerformanceObserver?

As I delve into exploring the performance APIs, I have come across window.performance and PerformanceObserver. These two functionalities seem to serve similar purposes. For instance, if I need to obtain the FCP time, I can retrieve it from performance.getE ...

How to Hide Validation Messages Automatically Using Knockout on Page Load

I have been facing a persistent issue where error messages are displaying onload and I want them to appear only on save. Although I have been successful in many cases and can adjust my code accordingly, this particular bug seems to be causing continuous pr ...

Element not producing output via Autocomplete from mui/material package

My challenge involves handling an array of states within the Autocomplete component. Once a state is selected, a corresponding component needs to be rendered based on the selection. However, despite successful state selection in the code, nothing is being ...

Tips for Locating an Element by Its Attribute in JQuery

I currently have a variable that holds a list of selects, and my goal is to filter out only those with a 'dependsOn' attribute set to 'EventType'. My initial attempt below doesn't seem to work as intended and returns a count of 0: ...