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

Passing the v-model property from a child component to a parent in VueJS

Consider a scenario where there is a Vue component structured like the following: Vue.component('child-comp',{ props:['name', 'val'], data: function(){ return { picked: '' } }, ...

The method of iterating over a string in key-value pairs

How can I efficiently loop through a string and extract key/value pairs? The data is provided to me as a single string using the jstorage plugin. I attempted to split the string into an array, but the resulting key/values were not as expected. For exampl ...

Error: Null value does not have a property 'tagName' to read

I am having trouble dynamically removing a CSS file from the head tag. I keep receiving this error message: Error: Unable to access property 'tagName' of null Here is my code: Link to CodeSandbox export default function IndexPage() { useEffe ...

Using Vuejs 2 to manage assets

As a beginner in VueJS, I am exploring ways to incorporate an external JavaScript library into my component. After downloading the minified JS file and placing it in my assets directory, I'm unsure how to compile my component to utilize this library ...

Unexpected behavior encountered with Angular module dependency injection

Having some difficulty managing dependencies for my node app. Here's the current structure: app.js var app = angular.module('myApp', ['myController', 'myFactory', 'rzModule', 'chart.js', 'myServ ...

`Inconsistencies between Postman and AngularJS service responses`

When I make a call to the endpoint using Postman, I receive this response: https://i.stack.imgur.com/pH31G.png However, when I make the same request from my AngularJS service defined below: this.login = function (loginInfo) { return $http({ ...

Avoiding line breaks when submitting data through Ajax calls is achievable by using the `.val` method

I've come across multiple articles discussing ways to add line breaks to the .val in jQuery, but unfortunately none of them have worked for me. I attempted using the recommended workaround provided by jQuery: $.valHooks.textarea = { get: function( ...

Is this jQuery script not functioning properly?

I came across this code on jsfiddle, and I really want to incorporate it into my PHP file. However, when I tried to do so, it didn't work even though I simply copied and pasted the code without making any changes. Here is my code: <!DOCTYPE html& ...

What makes YouTube videos load quicker on Chrome compared to Firefox?

After working as a Java UI & Backend developer for the past decade, I have come across some surprising browser behaviors: Firefox: When clicking on a related video on the YouTube website, there is a delay in figuring out the video followed by buffering ...

Navigating asynchronous URL parsing in NodeJS

I am still fairly new to the world of Node.js and Javascript, so I appreciate your patience with my confusion around the callback mechanism Bacchanalia. The Issue at Hand I'm currently working on a basic Node.js application that is responsible for h ...

What is the reason behind combining all states into a single location in Redux, even if they are not globally accessible?

As a newcomer to React and Redux, I have found them to be quite enjoyable when used together in a small sandbox application. However, as I consider larger applications, I can't help but question why Redux stores the entire application state in a singl ...

Tips on validating if a form has already been submitted using JavaScript and AJAX to prevent duplicate submissions

Exploring the world of web development, I stumbled upon a fascinating component - forms in JavaScript or jQuery. However, here lies my dilemma: In JS: const themeFolder = object_name.templateUrl; const urlAjax = themeFolder + '/FormHandler.php&apos ...

Ways to trigger an npm script from a higher-level directory?

After separately creating an express-based backend (in folder A) and a react-based front-end project (in folder B), I decided to merge them, placing the front-end project inside the back-end project for several advantages: No longer do I need to manu ...

Can the `lang` attribute be used in a `style` tag to specify the CSS preprocessor language for VueJS? Are there any disadvantages to using this method?

Occasionally, I notice people incorporating code like this: <style lang="scss"> ... </style> <style lang="stylus"> ... </style> I checked the documentation for the style tag and found that lang is not a valid a ...

Utilize Javascript to generate intricate table headers based on JSON data

I am currently facing a challenge in creating an HTML table header with colspan. I have a JSON object as follows: var metadata = [{ "colIndex": 0, "colType": "String", "colName": "PM" }, { "colIndex": 1, "colType": "String", "colName": "PR ...

Having issues with Angular Material, specifically with mat-list-item and routerLinkActive not functioning as expected

Currently, I am working with a navigation view that utilizes the MatSidenavModule. The issue I am encountering is on mobile screens. When I click a mat-list-item, the mat-sidenav closes as expected. However, upon opening the mat-sidenav again, Material alw ...

How does Chrome have the capability to access the gist json file? Isn't that typically not allowed?

Fetching a JSON file from Github Gist can sometimes be straightforward, but in certain situations, I have faced difficulties due to CORS restrictions. This has led me to resort to using JSONP instead. Can you shed some light on why this is the case? ...

What is the best way to split text copied from a textarea into <p> paragraphs with an equal number of characters in each?

Check out this JSFiddle version I've found a JSFiddle example that seems perfect for my current project needs. However, I'm wondering how to modify the code to ensure that each paragraph is evenly divided with the same number of characters and a ...

Altering the backdrop upon hovering over an element

As a beginner in Javascript and Jquery, I am working on creating an interactive feature where hovering over one element changes the background image in another column. I have managed to write the function, but now I want to add an animation to the image tr ...

Unlock the Power of Core 2 MVC with the Cutting-edge Integration of

Looking for a solution on how to effectively use JQuery Datatables with Core MVC? Check out this helpful resource: Using jQuery DataTables Grid With ASP.NET CORE MVC I recently downloaded the sample project and made some modifications to fit my needs. It ...