5. How to Avoid Large Layout Shifts in Magento 2
The next step is to fix the unexpected layout alterations that are causing your CLS scores to rise after you’ve analysed your web page and discovered them. Apply below given solutions to avoid large layout shifts.
5.1 Use placeholders when there is no ad available to show
Using placeholders for smooth loading of picture and video assets on the web page is also an advanced method.
This allows developers to utilise lower-resolution placeholder images that load faster on poor connections. It’s worth noting that the image and video width and height properties must still be specified in the code to prevent layout shifts.
5.2 Add Dimensions to Avoid Layout Shifts
By adding height and width properties to the page’s backend, you can set the image and video dimensions. Apply the height of the section or image/video which affects the layout of the page moves down when the site is loading.
These properties inform the web browser how much space is required for each picture and video on the page, based on the size of the user’s screen.
Large layout shifts are bound to happen when developers use CSS to resize and alter pictures and video elements on a web page.
This is due to the fact that page space for the image or video will only be allocated once it has been downloaded.
After downloading, it will take up some page space until it can be displayed where it belongs.
This results in a significant layout shift on the web page, resulting in an unattractive result.
5.3 Add width and height Attributes to Images and Videos
By adding height and width properties to the page’s backend, you can set the image and video dimensions.
These attributes tell the web browser how much space each image requires.
5.4 Reserve Space for Ads, Embeds and iFrames
This one is a bit more difficult to handle. Ads that trigger CLS can be dealt with by styling the element where the ad will appear. If you format the div to have unique heights and widths, for example, the ad would be limited to certain dimensions. If there is a shortage of supplies and an ad does not appear, there are two options. If an ad-containing feature does not display an ad, you may specify that an alternate banner ad or placeholder image be used to fill the space.
5.5 Optimize Font Delivery (FOUT/FOIT)
Flash of invisible text (FOIT) and Flash of Unstyled Text (FOUT) can also be caused by downloaded web fonts. Using rel=”preload” in the download link for the web font will help avoid this. Lighthouse can assist you in determining the cause of CLS.
6. CLS scores we achieved using above techniques