Improprove Your Website's Speed with Google PageSpeed Insights and Multiple JavaScript Files

Currently, I am working on optimizing my website according to Google's PageSpeed Insights recommendations. One of the suggestions is to "Remove Render-Blocking JavaScript" for a few files (for simplicity, let's call them 1.js, 2.js, and 3.js).

To address this issue, I am following Patrick Sexton's approach of "Defer Loading Javascript" by deferring only one file named defer.js:

<script type="text/javascript">
  function downloadJSAtOnload() {
    var element = document.createElement("script");
    element.src = "defer.js";
    document.body.appendChild(element);
  }
  if (window.addEventListener)
    window.addEventListener("load", downloadJSAtOnload, false);
  else if (window.attachEvent)
    window.attachEvent("onload", downloadJSAtOnload);
  else window.onload = downloadJSAtOnload;
</script>

My query now is: How can I tweak this method to include multiple files such as 1.js, 2.js, and 3.js?

Answer №1

If you're looking to streamline your JavaScript loading process, consider using HeadJS. I recently implemented it in a project and found it to be highly effective.

Answer №2

<script type="text/javascript">
    function loadJSFiles() {
        var files = ["js/1.js", "js/2.js", "js/3.js"],
            headTag = document.getElementsByTagName("head")[0],
            scriptTag, index;
        for (index = 0; index < files.length; index++) {
            scriptTag = document.createElement("script");
            scriptTag.src = files[index];
            headTag.appendChild(scriptTag);
        }
    }
    if (window.addEventListener)
        window.addEventListener("load", loadJSFiles, false);
    else if (window.attachEvent)
        window.attachEvent("onload", loadJSFiles);
    else window.onload = loadJSFiles;
</script>

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

What is the best approach to retrieve all items from DynamoDB using NodeJS?

I am trying to retrieve all the data from a DynamoDB table using Node.js. Here is my current code: const READ = async (payload) => { const params = { TableName: payload.TableName, }; let scanResults = []; let items; do { items = await ...

How can you initialize a JavaScript class that has a member variable of its own class?

I've come across an interesting puzzle. I am creating a class that can dynamically replicate itself to different levels, similar to an expandable menu. The initial definition looks like this: class MyClass { name: string = ''; fields ...

Creating an array with conditional elements in React involves utilizing the map method along with a conditional

My array, named tableFilterFields, looks something like this: const tableFilterFields = [ { label: "Start Date", name: "StartDate", type: FilterControls.DatePicker, defaultValue: new Date(new Date().setDate( ...

"Can you tell me the method for obtaining an array within an Angular

Within the realm of PHP, there exist certain elements within an array: $this->data['messages']['ms'][] = 'Line1'; $this->data['messages']['ms'][] = 'Line2'; along with a method that return ...

Make sure all of the inner tags are properly contained within their respective containers

In my explanatory bubble, I aim to include text within the explain-header div as a container for my explanations: /*Explain Bubble*/ .explain-container { position: relative; overflow: hidden; max-width: 70vw; max-height: 50vh; background-c ...

Maintain the original order of rows in the table while shuffling the columns they appear in randomly

I need help with my table setup. The left column contains words in English, while the right column has the same words translated into Korean. Is there a way to keep the rows intact while randomizing the order of the columns? Here's an example: <ta ...

Is there a way to interrupt a function in jquery before it completes its execution?

I've created a program that activates a sequence of 5 lights and sounds when a button is clicked, continuously looping through the sequence. There's another button labeled "cancel" to stop the loop midway and reset everything to the initial state ...

troubleshooting problems with feathers.JS using the npm start command

After developing two separate feathersJS applications, I encountered a situation where running npm start resulted in two unique types of errors for each app. How can I go about resolving this issue? View image here https://i.stack.imgur.com/RrsGW.pnghtt ...

Obtain ID from a PUT request using Axios in combination with React and Redux

I am facing an issue with making a PUT request to my server. The problem lies in obtaining the identifier for the specific object that needs to be updated. Currently, here is the code that I am working with: import axios from 'axios' import sett ...

Should we define all public methods or prototype each method separately?

Typically, when I create a library, my approach is as follows: var myLibrary = (function() { return { publicProperty: 'test', publicMethod: function() { console.log('public function'); }, ...

Recurrence of solely the middle segment of the separator's background picture

I have a unique divider image with fading top and bottom parts. I'm wondering if it's possible to use a sprite and 3 divs to only repeat the middle section, considering that my height is variable. Do I need separate images for the top, middle, an ...

Creating a unique AngularJS custom directive that utilizes ng-options can be achieved by populating

I've encountered a major roadblock in my project, and despite my efforts to troubleshoot, I can't seem to find the solution. The issue revolves around populating options within an ng-options directive through a service. This directive is nested i ...

What is the best way to eliminate or substitute Unicode Characters in Node.js 16?

Currently, I have a file that is being read into a JSON Object. { "city": "Delicias", "address": "FRANCISCO DOMÍN\u0002GUEZ 9" } We are using this address to send it to the Google Maps API in order to ...

How to shift an image to the right side of the navbar

Is it possible to change the position of an image within a navbar from left to right? I have tried using the float property but it doesn't seem to work. .logo-img{ float: right; margin: 0px 15px 15px 0px; } <a class="navbar-brand logo-img" ...

"Populate the input fields in a table with the data retrieved from the AJAX request's

For my current project, I am utilizing an ajax request to select data from a database. The selected data includes the area and floor number of a building, formatted as follows: "storey": [{ "storeyno": "1st Floor", &qu ...

Having trouble getting Highcharts SVG element to refresh? Looking to incorporate custom freeform drawing features within Highcharts?

I have implemented highchart for graph rendering and utilized the renderer to draw a custom line within the chart. I am looking for a way to recalculate and repaint this path whenever there is a change in data. The framework being used is highcharts-ng alo ...

What is the best method for properly inserting images into a Vue Carousel 3D slider?

I'm currently exploring the Vue Carousel 3D documentation and I am having trouble displaying a single image on each slide. Let me elaborate: I aim to create a slider similar to the one shown in the Controls Customized example in the documentation. Th ...

The document ready event does not fire upon page load, but can be triggered using the Developer Tools Console

When the ajax call is successful, the li element gets added to the ul. $.ajax({ .. success: function (response) { response.data.forEach(function (x) { $("#ulMain").append('<li class="liSub">' + x + &apo ...

Executing a function in Javascript following two callback functions

Help needed with handling JavaScript callback functions. I am currently using node Js and node-mysql for mysql queries in my application. The issue arises when new users register, as I need to perform 2 database checks: one to see if the email is already ...

What is the best way to dynamically adjust the size of a grid of divs to perfectly fit within the boundaries of a container div without surpassing them?

Currently, I am working on a project for "The Odin Project" that involves creating a web page similar to an etch-a-sketch. I have made some progress, but I am facing a challenge with dynamically resizing a grid of divs. The issue lies with the container d ...