Enhance LCP Performance in Next.js for Faster Loading Speeds

I'm currently working on a next.js project (version 11.1.2) and my goal is to improve the page speed performance. To track this, I am using Google PageSpeed Insight for evaluation. Presently, the scores stand at:

  • 40-50 for mobile (!!)
  • 80-90 for desktop.

A brief overview:
To enhance specific pages, I have implemented static site generation with incremental static generation. The crucial pages are built during the initial build time while the less significant ones are generated as required. These pages rely on data fetched from Postgres hosted on Heroku.

Steps taken so far:
Upon analyzing in Google PageSpeed Insight, it was evident that the LCP (Largest Contentful Paint) metric is considerably slow (around 6-7s). Therefore, I have already carried out the following tasks:

  • Optimized images by ensuring each page contains only one preloaded PNG image above the fold. I avoided using the native next/image-component due to variations in image sizes. For other images, I utilized the next/image-component.

  • In Google PageSpeed Insight, there was a recommendation to "Remove unused JS" present in two next.js files: "/chunks/..." and within the generated page. As a response, I:

  1. Conducted an analysis using next/bundle-analyzer which pinpointed a heavy library on the client-side. Subsequently, I switched to a lighter alternative but unfortunately did not see any notable improvements in speed.
  2. Concerning next/dynamic-imports, considering the usage of static site generation, I ponder if additional requests might contribute to a slowdown in performance.

As of now, I am uncertain if my approach is entirely correct. Are there any further optimizations I could implement? Any suggestions or guidance would be greatly appreciated! Thank you!

EDIT Below is the code snippet pertaining to the preloading of the image situated above the fold:

export function SingleItem({ item }){
// some logic

return(
 <>
  <Head>
    <link
       rel="preload"
       as="image"
       href={`/assets/pics/${item.name}.png`} />
   </Head>
   
   <div className={styles.image}>
     <ItemImage
       src={`/assets/pics/${item.name)}.png`}
       fallbackSrc="/assets/pic-coming-soon.jpg"
       alt="{`${item.name}`}" />
   </div>
   
   //more code
 </>
)}

The SingleItem-component is utilized in pages/item.js (SSG/ ISG). I am unsure about the feasibility of employing Head-Tags within components.

Furthermore, here is the ItemImage component code:

const ItemImage = (props) => {
  const { src, fallbackSrc, ...rest } = props;
  const [imgSrc, setImgSrc] = useState(src);
  const isSmallScreen = useMediaQuery("(max-width:780px)");

  return (
   <img
      {...rest}
      src={imgSrc}
      onError={() => {
        setImgSrc(fallbackSrc);
      }}
      className={`${isSmallScreen ? styles.smallImg : styles.bigImg}`}
    /> 
  );
};

//css:
//.bigImg {width: 100%; height: 100%}
//.smallImg {width: 70%; height: 70%}

Answer №1

Perhaps consider incorporating lazy loading for the images as a way to optimize page loading speed, especially since image files tend to be more resource-intensive.

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

Optimal strategies for designing navigation bars on contemporary websites

Struggling to find a solid answer for this dilemma. I have multiple html pages and a single navigation bar that I want to include on all pages for consistency. The idea of duplicating the html code for the navigation bar goes against everything I've l ...

JavaScript code for displaying data sequentially one at a time

Hey there, I've developed a function that pulls data from a jsonp file. However, I'm looking to display this data one by one - starting with the vendor's name followed by their policyUrl. If you want to check out the source code, click on t ...

How can you prevent the upload button from being clicked while a file is being uploaded and

By chance, I stumbled upon an issue that could potentially lead to a major problem with my application. I have developed an application where users can upload videos. Check out the Application here The main concern is that when a user uploads a video and ...

Assistance needed with selecting elements using jQuery

After some practice with jQuery, I managed to select this specific portion from a lengthy HTML file. My goal is to extract the values of subject, body, and date_or_offset (these are name attributes). How can I achieve this? Let's assume this snippet i ...

Tips for transferring query parameters in a redirect within NextJS

Whenever a user tries to access a page without authentication, I automatically redirect them to the login page. After that, I want to display a message to inform them of why they were redirected. However, I am encountering an issue with passing parameter ...

Issues with Braintree webhooks and CSRF protection causing malfunction

I have successfully set up recurring payments with Braintree and everything is functioning properly. Below is an example of my code: app.post("/create_customer", function (req, res) { var customerRequest = { firstName: req.body.first_name, lastN ...

Creating a div overlay triggered by the addition of a child tag

Using the Paypal zoid feature, I have a button that opens an iframe in the parent div when clicked. However, the iframe causes the other contents of the website to shift around, making it look messy. I'm wondering if there is a way to make the parent ...

Ways to Identify When the Back Button is Clicked

Currently, I am developing an HTML website that contains 4 divs on the index.html page. Initially, when clicking on a div, it would expand while the other sections reduced in width. However, the client requested that the URL should change when clicking o ...

I am unable to get the radio button checked in Angular 2

I have set up a form with two radio buttons for gender selection, and I want to ensure that the previously selected option is displayed as checked. Here's the code snippet I've added in my template: <div class="form-group"> <label& ...

Page jumping vertically in Chrome upon reload, with Firefox and Internet Explorer functioning properly

Utilizing this jQuery script, I am able to center a website vertically within the browser window if it exceeds the height of the outer wrapper-div, which has fixed dimensions. $( document ).ready(function() { centerPage(); )}; // center page vertic ...

Error: excessive recursion detected in <div ng-view="" class="ng-scope">

I've recently started learning angularJS and I've encountered an error that I need help with. Below is my index.html file: <body ng-app="myApp"> <div ng-view></div> <a href="table">click</a> <script ...

Troubleshooting Tips for Node.js and MongoDB Socket Closure Issue

I'm running into an issue while working on the login system for my NodeJS application. Everytime I attempt to retrieve a collection, MongoDB throws me this unusual error. The Error Message [MongoError: server localhost:27017 sockets closed] name: &a ...

How can we universally detect and resolve the user's language within a React/Next.js application using an Apollo client HOC?

Currently, I am developing an I18n module utilizing the Next.js framework (v5). The challenge I am facing is determining the user's default language universally in order to display the UI in that language. While it is relatively simple to resolve th ...

What is the most effective method for utilizing v-model with a pre-populated form in Vue.js?

Need some help with a form and looping through items in a module to generate textfields. Take a look at the photo for context: Link: https://i.sstatic.net/MPAVq.jpg Currently, I'm using a structure like this... <v-row class=" ...

Are there methods to individually style components that have been generated through the .map() function?

My goal is to style each <Tuner /> component separately, which are being rendered for each item in the this.state.notes array using this.state.notes.map(). I want to position them individually on the page, but currently they all appear together. This ...

Allow foreign characters with regex while excluding special symbols

While browsing, I came across this thread: Is there a regular expression to match non-English characters?. It provides a regex to remove foreign characters using the code snippet str = str.replace(/[^\x00-\x7F]+/g, "");. My goal is slightly diff ...

Encountering difficulty in adding content to a table using JavaScript. An error message appears stating that assignment to a function

I am utilizing ajax to retrieve an item from a web API, and then attempting to allocate attributes of that item to a table: function find() { var id = $('#contentID').val(); $.getJSON(uri + '/' + id) .done( ...

What is causing the cleanup function of useEffect to unexpectedly close a modal in Next.js?

I am currently working on implementing a modal dialog feature using the latest version of Next.JS (version 12.3.1). My goal is to have the modal open immediately, display a loading message while a request is being made, and then show the result of the requ ...

The size of my React Native app is significantly larger than expected once installed

I recently developed a React Native app, and while the release APK size is only 28 MBs, I was shocked to see that the storage size is a whopping 62 MBs. I am desperately looking for a solution as I need to deliver this project soon. Please help me resolv ...

Notify the user with a Jqgrid alert when they attempt to select multiple checkboxes

When editing rows, I wanted to avoid multiple selections. In order to achieve this, I need to check the condition if(count>1) and display an alert message. I am struggling to figure out how to retrieve the count of selected checkboxes in jqGrid. var m ...