Minimize the amount of external asynchronous calls made by the client

In my application, the client initiates multiple asynchronous JavaScript requests to third party servers. The issue I'm encountering is that when the client responds to these requests, the site becomes inactive for a brief period of time. This inactivity is multiplied with each subsequent request, resulting in overall inefficient loading times. For example, if x number of requests are sent and the average downtime per response is y milliseconds, then the total inefficiency can be calculated as x*y. I am looking for ways to consolidate these calls into a single one. Some of the third-party services I make calls to include Google Analytics and Google Ad Leads.

Here's an example of one of the calls I currently use:

function () {
      var oldonload = window.onload;
      window.onload = function(){
      __adroll_loaded=true;
      var scr = document.createElement("script");
      var host = (("https:" == document.location.protocol) ? "https://s.adroll.com" : "http://a.adroll.com");
      scr.setAttribute('async', 'true');
      scr.type = "text/javascript";
      scr.src = host + "/j/roundtrip.js";
      ((document.getElementsByTagName('head') || [null])[0] ||
      document.getElementsByTagName('script')[0].parentNode).appendChild(scr);
      if(oldonload){oldonload()}};
      }());

Answer №1

Let's talk about the impact of inline async javascript on browser performance. While inline async javascript does not block the browser, immediately invoked functions do. You can simplify your code by avoiding nesting the window.onload callback within an immediately invoked function.

My suggestion is to create a single function that handles all actions triggered by browser events. For instance:

window.onload = function() {
    //perform all tasks here
}

If feasible based on your app's structure, place this script right before the closing </body> tag.

This approach could optimize your script execution. I also advise analyzing your app's behavior during script execution. A useful tool for this task is Chrome developer tools (timeline tab).

Answer №2

The issue could potentially stem from adroll interfering with the window.onload event, which triggers after all page rendering is complete. To address this, consider utilizing jQuery (since you are likely calling other scripts already), obtain it from the Google URL to minimize downloads. Place it at the top of your HEAD tag for priority loading. For your code, incorporate a $(document).ready() function as shown below:

<!doctype html>
<html language="en">
<head>
    <title>My Webapp</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <!--// include other necessary library scripts here -->

... continue on with the HEAD and BODY content

    <!--// add any additional tracking code scripts like Google Analytics here-->

    <script>
        $(document).ready(new function () {

            //Include your onload code here, no longer obstructed

        });
    </script>

    <script type="text/javascript"> //followed by your adroll script
    (function () {
    var oldonload = window.onload;
    window.onload = function(){
       __adroll_loaded=true;
       var scr = document.createElement("script");
       var host = (("https:" == document.location.protocol) ? "https://s.adroll.com" : "http://a.adroll.com");
       scr.setAttribute('async', 'true');
       scr.type = "text/javascript";
       scr.src = host + "/j/roundtrip.js";
       ((document.getElementsByTagName('head') || [null])[0] ||
      document.getElementsByTagName('script')[0].parentNode).appendChild(scr);
       if(oldonload){oldonload()}};
    }());
    </script>
</body>
</html>

This method allows scripts to download in the background while enabling your code to execute unhindered. If the scripts indeed impede your code execution, introduce a timeout function to delay their loading briefly, such as:

    <script type="text/javascript"> //followed by your adroll script
    (function () {
        var oldonload = window.onload;
        window.onload = function(){
           setTimeout(function () {
               __adroll_loaded=true;
               var scr = document.createElement("script");
               var host = (("https:" == document.location.protocol) ? "https://s.adroll.com" :
                 "http://a.adroll.com");
               scr.setAttribute('async', 'true');
               scr.type = "text/javascript";
               scr.src = host + "/j/roundtrip.js";
               ((document.getElementsByTagName('head') || [null])[0] || 
                 document.getElementsByTagName('script')[0].parentNode).appendChild(scr);
           }, 500);
           if(oldonload){oldonload()}
       };
    }());
    </script>

By employing this approach, your code can proceed with its intended tasks promptly, while the adroll script executes asynchronously half a second later.

Answer №3

In order to decrease the number of JavaScript requests, a helpful strategy is bundling on the server side. This approach consolidates all necessary JS files into a single request, streamlining the process.

<script src='https://s.adroll.com/js/javascrpt1.js' type='text/javascript'></script>
<script src='https://s.adroll.com/js/javascrpt2.js' type='text/javascript'></script>
....
<script src='https://s.adroll.com/js/javascrpt100.js' type='text/javascript'></script>

Instead of multiple calls like above, consolidate them into one:

<script src='https://yourdomain/getAllJs' type='text/javascript'></script>

This method can also be made more versatile by allowing the passing of specific script filenames as parameters:

<script src='https://yourdomain/getjs?file=javascript1.js&file=javascript2.js&....file=javascript100.js' type='text/javascript'></script>

Depending on your server technology, there are different tools available such as Bundling and Minification in ASP.NET which streamline this process effortlessly here.

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

Unable to retrieve data from the specified location using axios in a Nuxt application

I am experiencing an issue where axios is not following my GET path when the project is built, although it works fine in dev mode. I am using this code to fetch local .html files and inject them into my vue component. <template> <div> ...

"Troubleshooting a callback problem in jQuery involving JavaScript and AJAX

UPDATE3 and FINAL: The problem has been resolved with the help of Evan and meder! UPDATE2: To clarify, I need the existing function updateFilters(a,b) to be called, not created. My apologies for any confusion. The issue with the code below is that udpate ...

What causes the disappearance of CSS styles when attempting to modify the className in react js?

I am currently working on a basic react application, and I am trying to dynamically change the name of a div element using the following code snippet - <div className={'changeTab ' + (page.login ? 'leftSide' : 'rightSide')} ...

Troubleshooting: Angular version 4.3 Interceptor malfunctioning

I have been trying to implement new interceptors in Angular 4.3 to set the authorization header for all requests, but it doesn't seem to be working. I placed a breakpoint inside the interceptor's 'intercept' method, but the browser didn ...

Tips on adding TypeScript annotations to an already existing global function

I'm contemplating enhancing an existing project by incorporating TypeScript type annotations. Struggling to supply an external declaration file for a straightforward example: app.ts: /// <reference path="types.d.ts"/> function welcome (person ...

If the Request does not recognize the OAuth key, generate a fresh new key

I am working with a React Native Frontend and an Express.js backend. The backend makes calls to a 3rd party API, which requires providing an OAuth key for the user that expires every 2 hours. Occasionally, when calling the API, I receive a 400 error indi ...

Is it possible for a jQuery ajaxSuccess function to detect an AJAX event in a separate JavaScript file? If it is, what steps am I missing?

I've been attempting to initiate a function following an ajax event. I have been informed that despite the ajax event occurring in a different file (on the same server, if that makes a difference) and that the file is javascript, not jquery, "Ajaxsucc ...

Building React Typescript Components with Froala Editor Plugins

Attempting to integrate a custom plugin into a Froala Editor within my React application using the package react-froala-wysiwyg. Following a tutorial on incorporating a custom popup/plugin found here. Encountering an issue due to TypeScript incompatibility ...

Extracting Unprocessed Data with Node.js Express

I am currently working with an Express server that handles a login form page: const app = express(); // part A app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.urlencoded()); app.get('/login', ...

Is there a way to capture the backdrop click event when clicking outside of an Angular UI Bootstrap modal?

I have encountered an issue in my application where I am using the $modal.open() function to display a modal popup that uses another page as a template. The popup works fine when clicked, and the Cancel button also functions correctly triggering the specif ...

`problem encountered when attempting to sanitize HTML through the npm package known as "sanitize-html"`

After researching the documentation, I attempted to use this code snippet: const dirty = '<div>Content</div>'; const clean = sanitizeHtml(dirty); The desired result of 'clean' should be "Content", however it seems that &apo ...

The PHP code encountered a syntax error due to an unexpected $EOF on the final empty line

I've been tasked with maintaining an old website that went offline due to script errors. I managed to resolve most of the issues in the script, but there's one error that's giving me trouble. The site is showing a syntax error that says "une ...

Navigate through a list of data in JSON format

After successfully implementing a jQuery AJAX call, I encountered difficulty in parsing the returned value. Working with a MySQL database, I am returning a PHP array() to my jQuery AJAX function using echo json_encode($reservationArray); Upon appending th ...

Organize an array based on its ratio

I am attempting to organize an array based on the win and lose ratio of each player. This is how my code currently looks: const array = [{playerName: 'toto', win: 2, lose: 2}, {playerName: 'titi', win: 0, lose: 0}, {playerName: &apo ...

Examine the syntax of JavaScript

I've been digging into a piece of code written by another person. My focus is on uncovering the JavaScript function that executes when the link below is clicked.... <a href="#subtabs_and_searchbar" id="finish_counting" onclick="$(' ...

Tips for adding new items to a Masonry Image List using React MUI

As I experiment with utilizing the React MUI Masonry Image List alongside the infinite scroll, I've found that they complement each other quite well. However, a challenge arises when appending new images to the Masonry image list. While I can success ...

What code can I use to prompt clients to refresh JavaScript files automatically?

We are experiencing an issue where, even after pushing out updates with new JavaScript files, client browsers continue to use the cached version of the file and do not display the latest changes. While we can advise users to perform a ctrlF5 refresh during ...

FilterService of PrimeNg

Looking for assistance with customizing a property of the p-columnFilter component. I have managed to modify the filter modes and customize the names, but I am having trouble with the no-filter option. Has anyone found a solution for this? this.matchMo ...

Screening data entries

.js "rpsCommonWord": [ { "addressWeightPct": "60", "charSubstituteWeightPct": "15", "nameWeightPct": "40", "oIdNumber": "21", "shortWordMinLthWeightPct": "100", "substituteWeightPct": "5", ...

What impact does nesting components have on performance and rendering capabilities?

Although this question may appear simple on the surface, it delves into a deeper understanding of the fundamentals of react. This scenario arose during a project discussion with some coworkers: Let's consider a straightforward situation (as illustrat ...