[Solved] Next JS Image's components are too slow to appear
Problem:
Next.js 10.0.7 and next-images 1.7 and big images take some seconds to appear.
See the components code below, but I think that there is a solution to my problem.
<Image height="600" width="800" src={ 'https://myImageURL.png' } alt="my image" />
Some questions:
- If we convert all images to .webp images is be shown faster?
- Is there a solution to this problem?
Solution 1:
The problem is that the default behavior of the Image Component is lazy loading.
We can change this behavior to eager by adding the loading prop like this: loading="eager"
or adding "priority={true}"
.
This property is only meant for advanced usage. Switch to an image to load with eager will normally bad performance. Nextjs recommend using the priority property, which properly loads the image eagerly.
The loading behavior of the image, default is lazy. When lazy load, it defers loading the image until it reaches a calculated distance from the viewport. Also when eager load adds, load the image immediately.
You can also try a second solution.
Solution 2:
You can add the sharp
package. Think that the default image processor of nextJS occurs this problem.
The next/image component's default loader uses an ultimate image optimizer that allows you to compress and compare images because it is quick to install and best for a development environment. When using the next start command in your production environment, it is recommended that you install sharp by running the yarn add sharp command in your project. This is not mandatory and necessary for Vercel deployment, because of sharp installed automatically. Install the sharp package in your project with this command below -
yarn add sharp
If sharp is already installed in your project but can't be resolved you can manually add the path to it via the NEXT_SHARP_PATH environment variable e.g. NEXT_SHARP_PATH=/tmp/node_modules/sharp
After adding sharp package
, your images were processed much faster than previously and there is no noticeable delay or late load anymore. if we try adding this before adding priority={true}
to every image, that will impact the site performance because lazy load not working that.
Thank you for reading the article. If you face any problems, please comment below.