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

Show only the present y-coordinate in the ToolTip of a chart.js

I am currently working on developing a chart using Chart.js, and my goal is to only show the y-axis value in the tooltip. The current display shows: date name_of_line: measurement example: Jan 1, 2020, 8:00:00 AM 5th Percentile: 100 oz. However, I would ...

The element is implicitly classified as an 'any' type due to the index expression not being of type 'number'

Encountering a specific error, I am aware of what the code signifies but unsure about the correct interface format: An error is occurring due to an 'any' type being implicitly assigned as the index expression is not of type 'number'. ...

Issue: Module 'serialize-javascript' not found despite being present in the 'node_modules' directory after executing npm start command in ReactJS project

My npm start suddenly stopped working. This issue arose after I switched to an unused branch with unrelated histories, made some changes, pushed them (unaware that the branch was outdated), then used git checkout -f "" to go back to the recent br ...

Using Angular with a hapi.js server that supports JSONP data requests

In my project, there is an endpoint specifically set at /api/profile that accepts post parameters. var http = require('http'); var serverConfig = require('../server.config.js'); var request = require('request'); module.expo ...

The structure of NodeJS Express API calls revolves around handling asynchronous events

Currently, I am working on a hobby project using NodeJS and Express, but I am finding it challenging to manage asynchronous calls. There is a bug that I would like the community's help in resolving. I have set up an Express layout where I send post r ...

Is there a way to mount or unmount a React component by pressing a single key?

I am currently developing an application that showcases 3D objects upon pressing certain keys on the keyboard. My goal is to have these objects disappear after 2-3 seconds or once the animation completes. Below is the component responsible for managing th ...

Leveraging reframe.js to enhance the functionality of HTML5 video playback

I'm struggling with using the reframe.js plugin on a page that includes HTML5 embedded video. When I try to use my own video file from the same folder, it doesn't work as expected. While everything seems to be working in terms of the page loadin ...

Selecting and Uploading Multiple Files in Internet Explorer (less than version 9)

I have been struggling with selecting and uploading multiple files at once to the server. Here is the code I am currently using: <html> <body> <form action="upload.php" method="post" enctype="multipart/form-data" name="myForm"> <l ...

Can you explain the significance of this code snippet 'true <=> false'?

Today I came across this piece of code: true <=> false. I'm a bit confused by it and don't really understand how it works. If anyone could shed some light on this expression for me, I would greatly appreciate it. For reference, this code ...

Reposition HTML elements using JavaScript

Is there a way to use JavaScript or jQuery to replace the image with class "fnone" located under the span element with class "ddlabel"? <span id="flat_title" class="ddTitleText "> <img class="fnone" src="images/pinc.png"> <span ...

The issue of infinite rendering caused by useState and how to effectively resolve it

I'm facing a strange issue in just a few lines of code, and I can't quite figure out what's happening behind the scenes. Here are the 4 lines causing trouble: function FarmerComponent(props) { let authCtx = useContext(AuthContext) let u ...

Ways to refresh a container

How do I update the box below... <div className="container team-member-tasks"> <header className="header-box"> <h1>Team Member Tasks</h1> ...after marking a task as complete using the script below. ...

Retrieving package information from NPM using a web browser

I am currently developing a Chrome Web App that retrieves information from NPM. However, I have encountered issues due to Chrome adhering to the Access-Control-Allow-Origin flags set by websites. While I am able to access the following URL: http://regist ...

Utilizing D3 to fetch geographic data in the form of a TopoJSON file for U.S. counties

After retrieving a set of coordinates, the goal is to use D3 to find the corresponding county from a U.S. TopoJSON file. Here is an example code snippet: navigator.geolocation.getCurrentPosition(function(position) { let coordinates: [number, number] = [p ...

Alert: Ajax encountered an issue with the auto-refreshing field

When running a script I created for a self-updating field, I encountered the following error message: UpdateField.html:37 Uncaught ReferenceError: fieldname is not defined at HTMLInputElement.onchange (UpdateField.html:37) Script: <!DOCTYPE ht ...

Why isn't CSS showing up in preview mode on the network tab?

I have been using nextjs for server-side rendering and I am encountering an issue where my CSS class is not being applied on the preview tab, it only works on the client side. Any idea why this is happening? Here is the code snippet: https://codesandbox.io ...

Tips for managing the ever-evolving language state in expressJS

I am currently working on a project utilizing nodeJs, handlebars, and the expressJs framework. I have implemented a language change functionality using the i18n-express module. This module adds a query string at the end of the URL when changing languages. ...

Struggling to delete a specific item by its ID from MongoDB within a Next.js application

Currently, I am building a todo app in nextjs to enhance my skills. However, I'm encountering some difficulties in deleting single todos from the database using the deleteOne function. Below is the frontend call: async function deleteTodo(id) { a ...

Tips for passing down props or all the properties of an object to create a dynamic component

I am facing an issue with a v-for loop in my project. The loop is supposed to iterate through objects in a list of todos fetched from the backend. These objects are then passed down to a child component, which displays each todo individually. However, I ha ...

What is the best way to determine which option is most suitable: types, classes, or function types in TypeScript for

Currently, I am developing a small todo command line utility with a straightforward program structure. The main file is responsible for parsing the command line arguments and executing actions such as adding or deleting tasks based on the input provided. E ...