{"id":2627,"date":"2022-06-06T23:26:37","date_gmt":"2022-06-06T22:26:37","guid":{"rendered":"https:\/\/marcosrego.com\/account\/?p=2627"},"modified":"2022-12-24T15:37:06","modified_gmt":"2022-12-24T15:37:06","slug":"avoid-layout-shift-mrutils","status":"publish","type":"post","link":"https:\/\/marcosrego.com\/account\/blog\/avoid-layout-shift-mrutils\/","title":{"rendered":"How to avoid (CLS) Layout Shift when using JS Components"},"content":{"rendered":"\n
When delaying JavaScript components, you might notice a layout shift that affects scoring. Fortunately, there are ways to fix that…<\/p>\n\n\n\n\n\n\n\n
When using components that are based on JavaScript, you might notice a layout shift on your content (CLS), especially if you delay the start of JavaScript in some way. In that situation, you’ll see the initial look of the elements until JavaScript kicks in.<\/p>\n\n\n\n
But of course, delaying JavaScript until user interaction or after some seconds it’s a good practice and a good trick to increase the score of a website on pagespeed insights<\/a>. So the better option is to find ways to avoid layout shifts, fortunately it is not that complicated.<\/p>\n\n\n\n For this tutorial, I’ll be focusing on Mr.Utils<\/a> JS components, but the same logic applies to other tools.<\/p>\n\n\n\n The way Mr.Utils JavaScript components work is by adding the necessary CSS inline properties to the element after page load, but only if the element doesn’t have a utility class that already uses some of those properties.<\/p>\n\n\n\n And as you might know, HTML classes don’t rely on JavaScript to apply the style of CSS properties. We’ll use that fact to our benefit, to avoid the layout shift when delaying JavaScript in this situation.<\/p>\n\n\n\n Components such as Mr.Utils Swipe component<\/strong> add the following inline properties to the element:<\/p>\n\n\n\n But there’s one utility class that does the exact same thing, so all you need to do is to add the following utility class after adding the swipe class:<\/p>\n\n\n\n If you are using Mr.Utils as a plugin: Instead of adding the class, you can select the option at Misc > Scroll > Horizontal Scroll.<\/p>\n\n\n\nUnderstand how general JS Components work<\/strong><\/span><\/h2>\n\n\n\n
Fixing the Content Layout Shift<\/strong><\/span><\/h2>\n\n\n\n
Fix CLS for components that add properties<\/strong><\/span><\/h3>\n\n\n\n
display: -webkit-inline-box;\nflex-wrap: unset !important;\noverflow-x: scroll !important;\n-webkit-overflow-scrolling: touch !important;\noverflow-y: hidden;<\/code><\/pre>\n\n\n\n
mr-horizontalscroll<\/code><\/pre>\n\n\n\n